手动实现shared_ptr

本文详细介绍了如何手动实现一个模板化的智能指针类,包括构造函数、拷贝构造函数、赋值构造函数和析构函数。智能指针用于管理动态分配的内存,通过引用计数来决定何时释放资源,防止内存泄漏。此外,还提供了获取值和引用计数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

手动实现范例:

template <class T> 
class MyPointer {
public:
    //普通构造函数, 设定T * ptr的值,并将引用计数设为1
    MyPointer(T * ptr) {
        ref = ptr;
        ref_count = new unsigned;
        *ref_count = 1;
    }

	//copy construct;
    MyPointer(MyPointer<T> &sptr) {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
    }

	//rewrite construct;
    MyPointer<T> & operator = (MyPointer<T> &sptr) {
        //同一个指针,直接返回
        if (this == &sptr)
            return *this;

        //如果计数值大于1,则旧指针计数值-1
        if(*ref_count > 0)
            remove();

        //把旧指针值给新指针
        ref = sptr.ref;
        ref_count = sptr.ref_count;

        //指针计数+1
        ++(*ref_count);
        return *this;
    }
    //deconstruct;
    ~MyPointer() {
        remove();
    }

    T getValue() {
        return *ref;
    }

    T getCount() {
        return static_cast<T>(*ref_count);
    }
protected:
    //delete ref;
    void remove() {
        --(*ref_count);

        //如果ref_count等于0,则销毁指针,并执行析构函数
        if (*ref_count == 0) {
            delete ref;
            delete ref_count;
            ref = NULL;
            ref_count = NULL;
        }
    }
private:
    unsigned * ref_count;    //应用计数值
    T * ref;                 //普通指针
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值