ref_ptr.hh (2778B)
1 #ifndef ref_ptr_hh_INCLUDED 2 #define ref_ptr_hh_INCLUDED 3 4 namespace Kakoune 5 { 6 7 struct RefCountable 8 { 9 RefCountable() = default; 10 RefCountable(const RefCountable&) {} 11 RefCountable(RefCountable&&) {} 12 virtual ~RefCountable() = default; 13 14 RefCountable& operator=(const RefCountable&) { return *this; } 15 RefCountable& operator=(RefCountable&&) { return *this; } 16 17 int refcount = 0; 18 }; 19 20 struct RefCountablePolicy 21 { 22 static void inc_ref(RefCountable* r, void*) noexcept { ++r->refcount; } 23 static void dec_ref(RefCountable* r, void*) noexcept { if (--r->refcount == 0) delete r; } 24 static void ptr_moved(RefCountable*, void*, void*) noexcept {} 25 }; 26 27 template<typename T, typename Policy = RefCountablePolicy> 28 struct RefPtr 29 { 30 RefPtr() = default; 31 explicit RefPtr(T* ptr) : m_ptr(ptr) { acquire(); } 32 ~RefPtr() noexcept { release(); } 33 RefPtr(const RefPtr& other) : m_ptr(other.m_ptr) { acquire(); } 34 RefPtr(RefPtr&& other) 35 noexcept(noexcept(moved(nullptr))) 36 : m_ptr(other.m_ptr) { other.m_ptr = nullptr; moved(&other); } 37 38 RefPtr& operator=(const RefPtr& other) 39 { 40 if (other.m_ptr != m_ptr) 41 { 42 release(); 43 m_ptr = other.m_ptr; 44 acquire(); 45 } 46 return *this; 47 } 48 49 RefPtr& operator=(RefPtr&& other) 50 { 51 release(); 52 m_ptr = other.m_ptr; 53 other.m_ptr = nullptr; 54 moved(&other); 55 return *this; 56 } 57 58 RefPtr& operator=(T* ptr) 59 { 60 if (ptr != m_ptr) 61 { 62 release(); 63 m_ptr = ptr; 64 acquire(); 65 } 66 return *this; 67 } 68 69 [[gnu::always_inline]] 70 T* operator->() const { return m_ptr; } 71 [[gnu::always_inline]] 72 T& operator*() const { return *m_ptr; } 73 74 [[gnu::always_inline]] 75 T* get() const { return m_ptr; } 76 77 [[gnu::always_inline]] 78 explicit operator bool() const { return m_ptr; } 79 80 void reset(T* ptr = nullptr) 81 { 82 if (ptr == m_ptr) 83 return; 84 release(); 85 m_ptr = ptr; 86 acquire(); 87 } 88 89 friend bool operator==(const RefPtr& lhs, const RefPtr& rhs) = default; 90 friend bool operator==(const RefPtr& lhs, const T* rhs) { return lhs.m_ptr == rhs; } 91 92 private: 93 T* m_ptr = nullptr; 94 95 [[gnu::always_inline]] 96 void acquire() 97 { 98 if (m_ptr) 99 Policy::inc_ref(m_ptr, this); 100 } 101 102 [[gnu::always_inline]] 103 void release() noexcept 104 { 105 if (m_ptr) 106 Policy::dec_ref(m_ptr, this); 107 } 108 109 [[gnu::always_inline]] 110 void moved(void* from) 111 noexcept(noexcept(Policy::ptr_moved(nullptr, nullptr, nullptr))) 112 { 113 if (m_ptr) 114 Policy::ptr_moved(m_ptr, from, this); 115 } 116 }; 117 118 } 119 120 #endif // ref_ptr_hh_INCLUDED