Last active
August 29, 2015 13:57
-
-
Save pallas/9652447 to your computer and use it in GitHub Desktop.
C++ reference counter base, with hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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