Skip to content

Instantly share code, notes, and snippets.

@jagt
Created June 18, 2013 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagt/5803251 to your computer and use it in GitHub Desktop.
Save jagt/5803251 to your computer and use it in GitHub Desktop.
simple smart ptr
#include <iostream>
using namespace std;
template<class T>
class Smart
{
private:
struct Body
{
T *ptr;
int count;
Body(T* p) : ptr(p), count(1) {}
~Body() { delete ptr; }
};
Body * body;
public:
Smart() : body(NULL) {}
Smart(T *p) : body(new Body(p)) {}
Smart(const Smart& smp) : body(smp.body)
{
if (body) ++(body->count);
}
Smart& operator= (const Smart& smp)
{
if (body != smp.body)
{
if (body && --(body->count) == 0)
{
delete body;
}
body = smp.body;
if (body)
{
++(body->count);
}
}
return *this;
}
~Smart()
{
if (body && --(body->count) == 0)
{
delete body;
}
}
int refcount()
{
return body ? body->count : 0;
}
T* operator-> () const
{
return body->ptr;
}
T& operator* () const
{
return *(body->ptr);
}
operator T* () const
{
return body->ptr;
}
};
struct Foo
{
int bar;
Foo() { cout << "const" << endl; }
~Foo() { cout << "dest" << endl; }
};
int main() {
Smart<Foo> smp = new Foo();
Smart<Foo> smp2 = smp;
Smart<Foo> smp3;
smp3 = smp2;
cout << "ref count:" << smp.refcount() << endl;
cout << "out of scope" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment