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

原文链接: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     try
22     {
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 Constructor
11     SmartPtr<int> p2(p1);
12     // Test Assignment Operator Overloaded
13     SmartPtr<int> p3(new int(1));
14     p3 = p1;
15     
16     return 0;
17 }
复制代码

  测试结果如下:

  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值