Created
June 18, 2013 07:09
-
-
Save jagt/5803251 to your computer and use it in GitHub Desktop.
simple smart ptr
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
#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