c++智能指针: shared_ptr,unique_ptr,weak_ptr,auto_ptr

本文深入探讨了C++中共享智能指针(shared_ptr)的基本原理与实现细节,包括其内部结构、操作符重载以及引用计数机制。通过具体代码示例,读者可以了解如何创建和使用shared_ptr,以及它如何帮助管理内存资源,避免内存泄漏。

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

一个简单的shared_ptr实现

一般来说,智能指针的实现需要以下步骤:
1.一个模板指针T* ptr,指向实际的对象。
2.一个引用次数(必须new出来的,不然会多个shared_ptr里面会有不同的引用次数而导致多次delete)。
3.重载operator*和operator->,使得能像指针一样使用shared_ptr。
4.重载copy constructor,使其引用次数加一。
5.重载operator=,如果原来的shared_ptr已经有对象,则让其引用次数减一并判断引用是否为零(是否调用delete)。
然后将新的对象引用次数加一。
6.重载析构函数,使引用次数减一并判断引用是否为零(是否调用delete)。

#ifndef __SHARED_PTR_
#define __SHARED_PTR_

template <typename T>
class shared_ptr {
public:
    shared_ptr(T* p) : count(new int(1)), _ptr(p) {}
    shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {}
    T* operator->() { return _ptr; }
    T& operator*() { return *_ptr; }
    shared_ptr<T>& operator=(shared_ptr<T>& other)
    {
        ++*other.count;
        if (this->_ptr && 0 == --*this->count)
        {
            delete count;
            delete _ptr;
        }
        this->_ptr = other._ptr;
        this->count = other.count;
        return *this;
    }
    ~shared_ptr()
    {
        if (--*count == 0)
        {
            delete count;
            delete _ptr;
        }
    }
    int getRef() { return *count; }
private:
    int* count;
    T* _ptr;
};
#endif

智能指针用法

https://www.cnblogs.com/TenosDoIt/p/3456704.html

https://blog.youkuaiyun.com/lisemi/article/details/93214336

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值