/**
* 智能指针,简单来讲是使用引用计数的方法,来跟踪监控指针。当引用计数为0时就delete 所跟踪的目标指针,释放内存
* 智能指针将一个指针封装到一个类中,当调用智能指针的拷贝构造函数时,将引用计数+1(因为新创建的智能指针也引用了目标指针)
* 重载智能指针的赋值操作符,等号左边的对象引用计数-1,右边的对象引用计数+1,右边的目标指针和引用计数赋值给左边的对象
* 智能指针的析构函数将引用计数-1,并判断是否为0,如果是的话delete 目标指针。
*/
template <class T>
class smart_ptr
{
private:
T* ptr;
int* count;
public:
smart_ptr(T* p = 0) : ptr(p), count(new int(0))
{
if (p) *count = 1;
}
smart_ptr(const smart_ptr& src)
{
++*src.count;
count = src.count;
ptr = src.ptr;
}
smart_ptr& operator =(const smart_ptr& src)
{
--*count;
if (*count == 0)
delete ptr;
count = src.count;
ptr = src.ptr;
}
const smart_ptr& operator =(const smart_ptr& src) const
{
--*count;
if (*count == 0)
delete ptr;
count = src.count;
ptr = src.ptr;
}
T* operator ->()
{
return ptr;
}
~smart_ptr()
{
--*count;
if (*count == 0)
{
delete ptr;
delete count;
ptr = NULL;
count = NULL;
}
}
};