C++智能指针及其简单实现

来源:互联网 发布:python接口自动化框架 编辑:程序博客网 时间:2024/04/29 10:31

原文链接:http://www.cnblogs.com/xiehongfeng100/p/4645555.html

基于引用计数的智能指针可以简单实现如下(详细解释见程序中注释):

复制代码
 1 #include <iostream> 2 using namespace std; 3  4 template<class T> 5 class SmartPtr 6 { 7 public: 8     SmartPtr(T *p); 9     ~SmartPtr();10     SmartPtr(const SmartPtr<T> &orig);                // 浅拷贝11     SmartPtr<T>& operator=(const SmartPtr<T> &rhs);    // 浅拷贝12 private:13     T *ptr;14     // 将use_count声明成指针是为了方便对其的递增或递减操作15     int *use_count;16 };17 18 template<class T>19 SmartPtr<T>::SmartPtr(T *p) : ptr(p)20 {21     try22     {23         use_count = new int(1);24     }25     catch (...)26     {27         delete ptr;28         ptr = nullptr;29         use_count = nullptr;30         cout << "Allocate memory for use_count fails." << endl;31         exit(1);32     }33 34     cout << "Constructor is called!" << endl;35 }36 37 template<class T>38 SmartPtr<T>::~SmartPtr()39 {40     // 只在最后一个对象引用ptr时才释放内存41     if (--(*use_count) == 0)42     {43         delete ptr;44         delete use_count;45         ptr = nullptr;46         use_count = nullptr;47         cout << "Destructor is called!" << endl;48     }49 }50 51 template<class T>52 SmartPtr<T>::SmartPtr(const SmartPtr<T> &orig)53 {54     ptr = orig.ptr;55     use_count = orig.use_count;56     ++(*use_count);57     cout << "Copy constructor is called!" << endl;58 }59 60 // 重载等号函数不同于复制构造函数,即等号左边的对象可能已经指向某块内存。61 // 这样,我们就得先判断左边对象指向的内存已经被引用的次数。如果次数为1,62 // 表明我们可以释放这块内存;反之则不释放,由其他对象来释放。63 template<class T>64 SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T> &rhs)65 {66     // 《C++ primer》:“这个赋值操作符在减少左操作数的使用计数之前使rhs的使用计数加1,67     // 从而防止自身赋值”而导致的提早释放内存68     ++(*rhs.use_count);69 70     // 将左操作数对象的使用计数减1,若该对象的使用计数减至0,则删除该对象71     if (--(*use_count) == 0)72     {73         delete ptr;74         delete use_count;75         cout << "Left side object is deleted!" << endl;76     }77 78     ptr = rhs.ptr;79     use_count = rhs.use_count;80     81     cout << "Assignment operator overloaded is called!" << endl;82     return *this;83 }
复制代码

  测试程序如下:

复制代码
 1 #include <iostream> 2 #include "smartptr.h" 3 using namespace std; 4  5 int main() 6 { 7     // Test Constructor and Assignment Operator Overloaded 8     SmartPtr<int> p1(new int(0)); 9     p1 = p1;10     // Test Copy Constructor11     SmartPtr<int> p2(p1);12     // Test Assignment Operator Overloaded13     SmartPtr<int> p3(new int(1));14     p3 = p1;15     16     return 0;17 }
复制代码

  测试结果如下:

  


0 0