kakoune/src/safe_ptr.hh

96 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 "backtrace.hh"
2015-02-23 21:39:56 +01:00
#include <type_traits>
#include <utility>
#ifdef SAFE_PTR_TRACK_CALLSTACKS
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
}
2015-02-23 21:39:56 +01:00
friend void inc_ref_count(const SafeCountable* sc, void* ptr)
{
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
friend void dec_ref_count(const SafeCountable* sc, void* ptr)
{
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(),
[=](const 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
}
2015-02-23 21:39:56 +01:00
friend void ref_ptr_moved(const SafeCountable* sc, void* from, void* to)
{
#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(),
[=](const 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
}
private:
#ifdef SAFE_PTR_TRACK_CALLSTACKS
struct Callstack
{
Callstack(void* p) : ptr(p) {}
void* ptr;
Backtrace bt;
};
2015-01-12 14:58:41 +01:00
mutable Vector<Callstack> m_callstacks;
#endif
mutable int m_count;
2015-02-23 21:39:56 +01:00
#else
[[gnu::always_inline]]
friend void inc_ref_count(const SafeCountable* sc, void* ptr) {}
[[gnu::always_inline]]
friend void dec_ref_count(const SafeCountable* sc, void* ptr) {}
#endif
};
2015-06-10 23:42:07 +02:00
template<typename T, typename U>
using PropagateConst = typename std::conditional<std::is_const<T>::value, const U, U>::type;
template<typename T>
using SafePtr = RefPtr<T, PropagateConst<T, SafeCountable>>;
2015-02-23 21:39:56 +01:00
}
#endif // safe_ptr_hh_INCLUDED