智能指针

一、请简述智能指针原理,并实现一个简单的智能指针。 

/**
*  智能指针,简单来讲是使用引用计数的方法,来跟踪监控指针。当引用计数为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;
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值