2014-04-25 20:27
题目:实现一个能够通过引用计数来实现自动回收数据的智能指针,用C++,不是java。
解法:这题真心牛,我的第一反应是发呆,因为对引用计数的了解仅限于这个名词,完全没办法建立模型。之后仔细把题解读了两遍之后,照样敲了一遍代码。然后边调试边阅读才有了些理解。引用计数有四点需要注意:1. 引用计数是个非负整数。2. 引用计数是对于一个实体变量的,所有指向这个实体的指针共用这个计数,所以就有了代码中的那种写法。3. 指针进行析构的时候,引用计数减一。4. 增加一个指针的时候,引用计数加一。
代码:
1 // 13.8 Implement a smart pointer class, which is capable of automatic garbage collection. Count of reference is the key to this problem. 2 // Answer: 3 // int *ref_count; 4 // referece count must be int *, instead of int. Think about why. 5 // The destructor function is called for (*ref_count) times, only at the last time the real data is freed. 6 #include <iostream> 7 using namespace std; 8 9 template <class T> 10 class Pointer { 11 public: 12 Pointer(T *ptr) { 13 data = ptr; 14 ref_count = new int(1); 15 }; 16 17 Pointer(Pointer<T> &p) { 18 data = p.data; 19 ref_count = p.ref_count; 20 ++(*ref_count); 21 }; 22 23 Pointer<T>& operator = (Pointer<T> &p) { 24 if (this == &p) { 25 // nothing to do. 26 return *this; 27 } 28 if (*ref_count > 0) { 29 remove(); 30 } 31 data = p.data; 32 ref_count = p.ref_count; 33 ++(*ref_count); 34 35 return *this; 36 }; 37 38 T getData() { 39 return *data; 40 }; 41 42 void setData(const T &val) { 43 *data = val; 44 }; 45 46 ~Pointer() { 47 remove(); 48 }; 49 protected: 50 T *data; 51 int *ref_count; 52 53 void remove() { 54 --(*ref_count); 55 if (*ref_count == 0) { 56 // if the reference count becomes 0, the data is never to be found again. 57 // it must be freed. 58 delete data; 59 data = nullptr; 60 delete ref_count; 61 ref_count = nullptr; 62 } 63 }; 64 }; 65 66 int main() 67 { 68 int *ptr = new int(7); 69 Pointer<int> p1(ptr); 70 Pointer<int> p2(p1); 71 72 cout << p1.getData() << endl; 73 p2.setData(12); 74 cout << p2.getData() << endl; 75 76 return 0; 77 }