实例如下:
写的不太标准,主要参考c++ primer中的讲解
#include <iostream>
using namespace std;
class counter
{
int m_use;
template <class T> friend class smartpointer;
counter(int use):m_use(use){}
counter(){ m_use = 0;}
};
template <class T>
class smartpointer
{
public:
smartpointer(T *ptr):m_pt(ptr),m_cnt(new counter(1))
{
cout<<"smartpointer::smartpointer() invoked " << m_cnt->m_use++ <<endl;
}
smartpointer(const smartpointer<T>& rhs)
{
m_pt = rhs.m_pt;
m_cnt = rhs.m_cnt;
++(m_cnt->m_use);
cout<<"smartpointer::smartpointer(const smartpointer&) invoked " << m_cnt->m_use++ <<endl;
}
~smartpointer()
{
cout<<"SmartPointer::~SmartPointer() invoded" << m_cnt->m_use <<endl;
if(--(m_cnt->m_use) == 0)
{
delete m_pt;
delete m_cnt;
}
}
smartpointer& operator=(const smartpointer& rhs)
{
if(rhs == *this)
return *this;
m_pt = rhs.m_pt;
m_cnt = rhs.m_cnt;
++(m_cnt->m_use);
cout<<"SmartPointer::operator=SmartPointer() invoded" << m_cnt->m_use <<endl;
return *this;
}
private:
T *m_pt;
counter *m_cnt;
};
class test
{
private:
int t;
int *value;
public:
test(int v):t(v), value(& v)
{
cout << t <<endl;
}
~test()
{
delete value;
cout << "test::~test() invoked" <<endl;
}
};
int main(int argc, char *argv[])
{
test *t = new test(10);
smartpointer<test> pp(t);
smartpointer<test> pp2(pp);
smartpointer<test> pp3 = pp2;
return 0;
}
写的不太标准,主要参考c++ primer中的讲解