shared_ptr简单实现

来源:互联网 发布:android电视直播软件 编辑:程序博客网 时间:2024/05/16 07:21

实现一个简单的shared_ptr

翻看以前的代码的时候发现一个shared_ptr的简单实现。

我记得是网上的一篇例子(好像改了一点),但是又懒得找出处了 ╮(╯▽╰)╭。

觉得这份代码足以用来初步了解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)。

 

源码如下:

复制代码
 1 #ifndef __SHARED_PTR_ 2 #define __SHARED_PTR_ 3  4 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 };36 37 38 #endif
复制代码
原创粉丝点击