Skip to content

Instantly share code, notes, and snippets.

@damian-rzeszot
Last active June 15, 2018 23:35
Show Gist options
  • Save damian-rzeszot/24a25354eb0fdd28c5c49340a971a72d to your computer and use it in GitHub Desktop.
Save damian-rzeszot/24a25354eb0fdd28c5c49340a971a72d to your computer and use it in GitHub Desktop.
strong_pointer.cpp
template<class T>
class Reference {
T* _pointer;
size_t _count;
public:
Reference(T* pointer) {
pointer = pointer;
_count = 1;
}
~Reference() {
delete _pointer;
}
void retain() {
_count++;
}
bool release() {
_count--;
return _count == 0;
}
size_t count() {
return _count;
}
};
template <class T>
class StrongPointer {
Reference<T>* _reference;
public:
StrongPointer() {
_reference = NULL;
}
StrongPointer(T* pointer) {
_reference = new Reference<T>(pointer);
}
~StrongPointer() {
release();
}
void operator=(const StrongPointer<T>& other) {
assert(_reference != other._reference);
release();
_reference = other._reference;
_reference->retain();
}
void operator=(T* pointer) {
release();
_reference = new Reference<T>(pointer);
}
void release() {
if (_reference && _reference->release()) {
delete _reference;
_reference = NULL;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment