safe_ptr.hh (2558B)
1 #ifndef safe_ptr_hh_INCLUDED 2 #define safe_ptr_hh_INCLUDED 3 4 // #define SAFE_PTR_TRACK_CALLSTACKS 5 6 #include "assert.hh" 7 #include "ref_ptr.hh" 8 9 #ifdef SAFE_PTR_TRACK_CALLSTACKS 10 #include "backtrace.hh" 11 #include "vector.hh" 12 #include <algorithm> 13 #endif 14 15 namespace Kakoune 16 { 17 18 // *** SafePtr: objects that assert nobody references them when they die *** 19 20 class SafeCountable 21 { 22 public: 23 #ifdef KAK_DEBUG 24 SafeCountable() {} 25 ~SafeCountable() 26 { 27 kak_assert(m_count == 0); 28 #ifdef SAFE_PTR_TRACK_CALLSTACKS 29 kak_assert(m_callstacks.empty()); 30 #endif 31 } 32 33 SafeCountable(const SafeCountable&) {} 34 SafeCountable(SafeCountable&&) {} 35 36 SafeCountable& operator=(const SafeCountable& other) { return *this; } 37 SafeCountable& operator=(SafeCountable&& other) { return *this; } 38 39 private: 40 friend struct SafeCountablePolicy; 41 #ifdef SAFE_PTR_TRACK_CALLSTACKS 42 struct Callstack 43 { 44 Callstack(void* p) : ptr(p) {} 45 void* ptr; 46 Backtrace bt; 47 }; 48 49 mutable Vector<Callstack> m_callstacks; 50 #endif 51 mutable int m_count = 0; 52 #endif 53 }; 54 55 struct SafeCountablePolicy 56 { 57 #ifdef KAK_DEBUG 58 static void inc_ref(const SafeCountable* sc, void* ptr) noexcept 59 { 60 ++sc->m_count; 61 #ifdef SAFE_PTR_TRACK_CALLSTACKS 62 sc->m_callstacks.emplace_back(ptr); 63 #endif 64 } 65 66 static void dec_ref(const SafeCountable* sc, void* ptr) noexcept 67 { 68 --sc->m_count; 69 kak_assert(sc->m_count >= 0); 70 #ifdef SAFE_PTR_TRACK_CALLSTACKS 71 auto it = std::find_if(sc->m_callstacks.begin(), sc->m_callstacks.end(), 72 [=](const SafeCountable::Callstack& cs) { return cs.ptr == ptr; }); 73 kak_assert(it != sc->m_callstacks.end()); 74 sc->m_callstacks.erase(it); 75 #endif 76 } 77 78 static void ptr_moved(const SafeCountable* sc, void* from, void* to) noexcept 79 { 80 #ifdef SAFE_PTR_TRACK_CALLSTACKS 81 auto it = std::find_if(sc->m_callstacks.begin(), sc->m_callstacks.end(), 82 [=](const SafeCountable::Callstack& cs) { return cs.ptr == from; }); 83 kak_assert(it != sc->m_callstacks.end()); 84 it->ptr = to; 85 #endif 86 } 87 #else 88 static void inc_ref(const SafeCountable*, void* ptr) noexcept {} 89 static void dec_ref(const SafeCountable*, void* ptr) noexcept {} 90 static void ptr_moved(const SafeCountable*, void*, void*) noexcept {} 91 #endif 92 }; 93 94 template<typename T> 95 using SafePtr = RefPtr<T, SafeCountablePolicy>; 96 97 } 98 99 #endif // safe_ptr_hh_INCLUDED