C++ reference counter base, with hook
// All rights reserved, | |
// Derrick Pallas | |
// License: zlib | |
#ifndef COUNTABLE_H | |
#define COUNTABLE_H | |
#include <cassert> | |
template <class T> | |
class countable { | |
public: | |
countable() : r(0) { } | |
~countable() { assert(!r); } | |
unsigned refs() { return r; } | |
bool collect() { return true; } | |
static T* get(T * t) { | |
++t->r; | |
return t; | |
} | |
static bool put(T * t) { | |
assert(t->refs()); | |
if (--t->r) | |
return false; | |
if (t->collect()) | |
delete t; | |
return true; | |
} | |
private: | |
countable(const countable &); | |
countable & operator=(const countable &); | |
unsigned r; | |
}; | |
namespace ref { | |
template <class T> T* get(T * t) { return countable<T>::get(t); } | |
template <class T> bool put(T * t) { return countable<T>::put(t); } | |
} | |
#endif//COUNTABLE_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment