#include <iostream>
using namespace std;
template<typename Type>//引用计数的智能指针
class auto_ptr_
{
public:
auto_ptr_(Type *t = NULL):ptr(t), count(1)
{
}
auto_ptr_(const auto_ptr_<Type>& at) :ptr(at.ptr), count(at.count+1)
{}
auto_ptr_<Type>& operator=(const auto_ptr_<Type> &at)
{
if (this != &at)
{
if (ptr != NULL)
{
if (count == 1)
this->~auto_ptr_();//如果ptr已经存在且唯一指向目标。
ptr = at.ptr;
count = at.count + 1;
}
}
return *this;
}
~auto_ptr_()
{
if (count == 1)
{
if (ptr != NULL)
{
delete ptr;
ptr = NULL;
}
}
}
Type* operator->()
{
return ptr;
}
Type& operator*()
{
return *this;
}
private:
Type *ptr;
int count;
};
int main()
{
int *a = new int(3);
int *b = new int(4);
auto_ptr_<int> ps(a);
auto_ptr_<int> pb(ps);
auto_ptr_<int> pc(b);
pc=pb;
auto_ptr_<int> pd(pc);
return 0;
}
原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46566705