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 };
shared_ptr
最新推荐文章于 2024-10-06 14:42:09 发布
本文详细介绍了C++中智能指针`shared_ptr`的实现,包括构造函数、拷贝构造函数、赋值运算符以及析构函数的用法。`shared_ptr`通过内部的计数器管理对象的生命周期,确保了对象在没有引用时被正确删除。此外,还展示了`getRef`方法用于获取引用计数值。
摘要由CSDN通过智能技术生成