#include <iostream>
using namespace std;
template <typename T>
class SmartPointer{
public:
SmartPointer(T *p=0):poin(p),use(new size_t(1)){}
SmartPointer(const SmartPointer &p){
if(this!=&p)
{
poin = p.poin;
use = p.use;
++(*use);
}
}
SmartPointer& operator=(const SmartPointer &tmp)
{
if(poin==tmp.poin)
return *this;
++*tmp.use;
if(--*use==0)
{
cout<<"析构函数被调用了"<<endl;
delete poin;
delete use;
}
poin = tmp.poin;
use = tmp.use;
return *this;
}
T& operator*()
{
cout<<"get in"<<endl;
return *poin;
}
~SmartPointer()
{
if(--(*use)==0)
{
cout<<"析构函数调用"<<endl;
delete poin;
delete use;
}
}
void Print()
{
cout<<*use<<" "<<*poin<<endl;
}
private:
T *poin;
size_t *use;
};
int main()
{
SmartPointer<int> a(new int(4));
a.Print();
SmartPointer<int> c;
c=a;
cout<<"a........."<<endl;
a.Print();
cout<<"c........."<<endl;
c.Print();
return 0;
}
智能指针类的实现
最新推荐文章于 2024-03-11 21:48:10 发布