以下為智能指針的demo。
設計思路為:通過一個引用計數的指針在多個auto_ptr<Type>中共享Type對象。
1 // auto_ptr.h
2 #include <iostream>
3 namespace myspace
4 {
5 template <class T>
6 class auto_ptr
7 {
8 T *t; // 指針對象
9 size_t *use; // 引用計數,采用指針的方式是為了方便多個auto_ptr的共享
10 public:
11 //!< 一般構造函數
12 auto_ptr(T *obj)
13 : t(obj) // 接收指針
14 , use(new size_t(1)) // 創(chuàng)建引用計數
15 {
16 }
17 //!< 拷貝構造函數
18 auto_ptr(const auto_ptr<T> &ptr)
19 : t(ptr.t)
20 , use(ptr.use)
21 {
22 ++*(ptr.use); // 傳遞引用計數后,計數值+1
23 }
24 ~auto_ptr()
25 {
26 // 每次析構的時候,如果計數值為0則刪除對象
27 if (--*use == 0)
28 {
29 delete t;
30 delete use;
31 }
32 }
33 //!< ->操作符重載
34 T* operator-> () const
35 {
36 return t;
37 }
38 //!< *操作符重載,返回指針對象的引用
39 T& operator* () const
40 {
41 return *t;
42 }
43 };
44
45 //!< 流輸出,采用了*操作符,所以不需要設為friend
46 template <class Type>
47 std::ostream& operator<< (std::ostream &os, auto_ptr<Type> ptr)
48 {
49 os << *ptr;
50 return os;
51 }
52 }//end of myspace
53
54 // main.cpp
55 #include <iostream>
56 #include "auto_ptr.h"
57 #ifdef _DEBUG
58 #define new new (_NORMAL_BLOCK, __FILE__, __LINE__)
59 #endif
60 int main(int argc, _TCHAR* argv[])
61 {
62 myspace::auto_ptr<int> iptr(new int(9)) ;
63 std::cout << iptr << std::endl;
64 ++ *iptr;
65 std::cout << iptr << std::endl;
66 (*iptr) --;
67 std::cout << iptr << std::endl;
68 getchar();
69 return 0;
70 }
71
從上面的Demo中,可以看到這個智能指針的缺點:
每次創(chuàng)建智能指針的時候,傳入的指針是對外暴露的,采用new的方式作為入參才能保證安全的。如果這個new出來的對象(如上面的int(9))在別處被delete了,繼續(xù)使用這個智能指針相當于使用一個野指針。這樣的問題即便是boost的share_ptr也是會有的。