shared_ptr

本文详细介绍了C++中智能指针`shared_ptr`的实现,包括构造函数、拷贝构造函数、赋值运算符以及析构函数的用法。`shared_ptr`通过内部的计数器管理对象的生命周期,确保了对象在没有引用时被正确删除。此外,还展示了`getRef`方法用于获取引用计数值。
摘要由CSDN通过智能技术生成
template <typename T>
 5 class shared_ptr {
 6 public:
 7     shared_ptr(T* p) : count(new int(1)), _ptr(p) {}
 8     shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {}
 9     T* operator->() { return _ptr; }
10     T& operator*() { return *_ptr; }
11     shared_ptr<T>& operator=(shared_ptr<T>& other)
12     {
13         ++*other.count;
14         if (this->_ptr && 0 == --*this->count)
15         {
16             delete count;
17             delete _ptr;
18         }
19         this->_ptr = other._ptr;
20         this->count = other.count;
21         return *this;
22     }
23     ~shared_ptr()
24     {
25         if (--*count == 0)
26         {
27             delete count;
28             delete _ptr;
29         }
30     }
31     int getRef() { return *count; }
32 private:
33     int* count;
34     T* _ptr;
35 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值