Skip to content

Instantly share code, notes, and snippets.

@ariscop ariscop/Output

Last active Aug 29, 2015
Embed
What would you like to do?
C++ Ref counting template
Sizeof Integer: 48
Sizeof Ref<Integer>: 8
Refcount is 1
Refcount is 2
Value: 12
Refcount is 1
Refcount is 0
#include <stdio.h>
#include <vector>
template <typename T>
class Ref
{
public:
Ref(T *pointer) {
this->pointer = pointer;
this->pointer->_ref();
}
Ref(const Ref<T>& other) {
this->pointer = other.pointer;
this->pointer->_ref();
};
~Ref() {
this->pointer->_unref();
}
T *operator->() const {
return this->pointer;
}
protected:
T *pointer;
private:
// Don't allow heap alocation
void* operator new(size_t);
void* operator new[](size_t);
void operator delete(void*);
void operator delete[](void*);
};
class Counted
{
private:
int count;
protected:
template <typename T>
friend class Ref;
Counted() : count(0) {};
virtual ~Counted() {};
void _ref() {
this->count++;
printf("Refcount is %d\n", this->count);
}
void _unref() {
this->count--;
printf("Refcount is %d\n", this->count);
if(!this->count)
delete this;
}
};
class Integer : public Counted
{
public:
Integer(int value) {
this->value = value;
}
int value;
int pad, out, type, to, more, than, eight, bytes;
};
int main(int argc, char *argv[])
{
printf("Sizeof Integer: %lu\n", sizeof(Integer));
printf("Sizeof Ref<Integer>: %lu\n", sizeof(Ref<Integer>));
Ref<Integer> intref = new Integer(12);
Ref<Integer> ref2 = intref;
printf("Value: %d\n", ref2->value);
auto vec = new std::vector<int>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.