以下為智能指針的demo。
設(shè)計(jì)思路為:通過(guò)一個(gè)引用計(jì)數(shù)的指針在多個(gè)auto_ptr<Type>中共享Type對(duì)象。
1 // auto_ptr.h
2 #include <iostream>
3 namespace myspace
4 {
5 template <class T>
6 class auto_ptr
7 {
8 T *t; // 指針對(duì)象
9 size_t *use; // 引用計(jì)數(shù),采用指針的方式是為了方便多個(gè)auto_ptr的共享
10 public:
11 //!< 一般構(gòu)造函數(shù)
12 auto_ptr(T *obj)
13 : t(obj) // 接收指針
14 , use(new size_t(1)) // 創(chuàng)建引用計(jì)數(shù)
15 {
16 }
17 //!< 拷貝構(gòu)造函數(shù)
18 auto_ptr(const auto_ptr<T> &ptr)
19 : t(ptr.t)
20 , use(ptr.use)
21 {
22 ++*(ptr.use); // 傳遞引用計(jì)數(shù)后,計(jì)數(shù)值+1
23 }
24 ~auto_ptr()
25 {
26 // 每次析構(gòu)的時(shí)候,如果計(jì)數(shù)值為0則刪除對(duì)象
27 if (--*use == 0)
28 {
29 delete t;
30 delete use;
31 }
32 }
33 //!< ->操作符重載
34 T* operator-> () const
35 {
36 return t;
37 }
38 //!< *操作符重載,返回指針對(duì)象的引用
39 T& operator* () const
40 {
41 return *t;
42 }
43 };
44
45 //!< 流輸出,采用了*操作符,所以不需要設(shè)為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中,可以看到這個(gè)智能指針的缺點(diǎn):
每次創(chuàng)建智能指針的時(shí)候,傳入的指針是對(duì)外暴露的,采用new的方式作為入?yún)⒉拍鼙WC安全的。如果這個(gè)new出來(lái)的對(duì)象(如上面的int(9))在別處被delete了,繼續(xù)使用這個(gè)智能指針相當(dāng)于使用一個(gè)野指針。這樣的問(wèn)題即便是boost的share_ptr也是會(huì)有的。