智能指针的实现

智能指针模板类的实现,主要有几个关键点,

首先是如何实现不同对象的引用记数,才能保证当引用记数增减之后可以,所有对象的引用记数都同步增减;

所以不能简单的用一个unsigned成员,因为每个对象中成员的值会各不相同,

用一个unsigned指针就可以了,当初始化时从堆中动态分配一个unsigned,

另外,再做了赋值操作和析构操作之后要检查引用记数是否变为0。

 1 tempate<typename T> class SmartPointer {
 2     public:
 3         SmartPointer(T *ptr) {
 4             ref = ptr;
 5             ref_count = (unsigned*)malloc(sizeof(unsigned));
 6         }
 7         SmartPointer(const SmartPointer<T> &sptr) {
 8             ref = sptr.ref;
 9             ref_count = sptr.ref_count;
10             ++*ref_count;
11         }
12         SmartPointer<T>& operator=(const SmartPointer<T>& sptr) {
13             if (this != &sptr) {
14                 if (--*ref_count == 0) {
15                     clear();
16                 }
17                 ref = sptr.ref;
18                 ref_count = sptr.ref_count;
19                 ++*ref_count;
20             }
21             return *this;
22         }
23         ~SmartPointer() {
24             if (--*ref_count == 0) {
25                 clear();
26             }
27         }
28         T getValue() {
29             return *ref;
30         }
31     private:
32         void clear() {
33             delete ref;
34             free(ref_count);
35             ref = NULL;
36             ref_count = NULL;
37         }
38     protected:
39         T *ref;
40         unsigned *ref_count;
41 }
原文地址:https://www.cnblogs.com/chasuner/p/smartpointer.html