kakoune/src/safe_ptr.hh

97 lines
2.3 KiB
C++
Raw Normal View History

#ifndef safe_ptr_hh_INCLUDED
#define safe_ptr_hh_INCLUDED
// #define SAFE_PTR_TRACK_CALLSTACKS
#include "assert.hh"
2015-02-23 21:39:56 +01:00
#include "ref_ptr.hh"
#include <type_traits>
#include <utility>
#ifdef SAFE_PTR_TRACK_CALLSTACKS
2016-12-03 14:18:11 +01:00
#include "backtrace.hh"
2015-01-12 14:58:41 +01:00
#include "vector.hh"
#include <algorithm>
#endif
namespace Kakoune
{
// *** SafePtr: objects that assert nobody references them when they die ***
class SafeCountable
{
public:
#ifdef KAK_DEBUG
SafeCountable() : m_count(0) {}
~SafeCountable()
{
kak_assert(m_count == 0);
#ifdef SAFE_PTR_TRACK_CALLSTACKS
kak_assert(m_callstacks.empty());
#endif
}
private:
friend struct SafeCountablePolicy;
#ifdef SAFE_PTR_TRACK_CALLSTACKS
struct Callstack
{
Callstack(void* p) : ptr(p) {}
void* ptr;
Backtrace bt;
};
mutable Vector<Callstack> m_callstacks;
#endif
mutable int m_count;
#endif
};
struct SafeCountablePolicy
{
#ifdef KAK_DEBUG
2017-01-31 22:45:55 +01:00
static void inc_ref(const SafeCountable* sc, void* ptr) noexcept
{
2015-02-23 21:39:56 +01:00
++sc->m_count;
#ifdef SAFE_PTR_TRACK_CALLSTACKS
2015-02-23 21:39:56 +01:00
sc->m_callstacks.emplace_back(ptr);
#endif
}
2015-02-23 21:39:56 +01:00
2017-01-31 22:45:55 +01:00
static void dec_ref(const SafeCountable* sc, void* ptr) noexcept
{
2015-02-23 21:39:56 +01:00
--sc->m_count;
kak_assert(sc->m_count >= 0);
#ifdef SAFE_PTR_TRACK_CALLSTACKS
2015-02-23 21:39:56 +01:00
auto it = std::find_if(sc->m_callstacks.begin(), sc->m_callstacks.end(),
2017-01-21 13:10:24 +01:00
[=](const SafeCountable::Callstack& cs) { return cs.ptr == ptr; });
2015-02-23 21:39:56 +01:00
kak_assert(it != sc->m_callstacks.end());
sc->m_callstacks.erase(it);
#endif
}
2017-01-31 22:45:55 +01:00
static void ptr_moved(const SafeCountable* sc, void* from, void* to) noexcept
{
#ifdef SAFE_PTR_TRACK_CALLSTACKS
2015-02-23 21:39:56 +01:00
auto it = std::find_if(sc->m_callstacks.begin(), sc->m_callstacks.end(),
2017-01-21 13:10:24 +01:00
[=](const SafeCountable::Callstack& cs) { return cs.ptr == from; });
2015-02-23 21:39:56 +01:00
kak_assert(it != sc->m_callstacks.end());
it->ptr = to;
#endif
}
2015-02-23 21:39:56 +01:00
#else
2017-01-31 22:45:55 +01:00
static void inc_ref(const SafeCountable*, void* ptr) noexcept {}
static void dec_ref(const SafeCountable*, void* ptr) noexcept {}
static void ptr_moved(const SafeCountable*, void*, void*) noexcept {}
#endif
};
2015-06-10 23:42:07 +02:00
template<typename T>
using SafePtr = RefPtr<T, SafeCountablePolicy>;
2015-02-23 21:39:56 +01:00
}
#endif // safe_ptr_hh_INCLUDED