实现STL的shared_ptr指针

实现shared_ptr指针

一般来说,实现一个shared_ptr需要实现这几个操作:

1.构造函数,进行初始化操作。
2.拷贝构造函数,让拷贝的shared_ptr的引用计数进行加一操作
3.重载->操作符,得到对应的对象指针。
4.重载*操作符,得到对应的对象。
5.重载=操作符,需要将赋值符左边的shared_ptr的引用计数进行-1操作,如果左边的引用计数为0的话,则进行销毁。将赋值符右边的进行+1操作。然后将右边的引用计数和对象赋给左边。
6.析构函数,如果当前的引用计数为0的话就调用delete进行销毁,否则引用计数减1.
7.获取引用计数。

4template <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;//引用计数加1
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 };
发布了40 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/suoyudong/article/details/104886339