资源共享型智能指针实现方式
【1】資源共享型智能指針實現方式簡述
資源共享型的智能指針有兩種實現方式:一種是侵入式;一種是非侵入式。
?
網上以及書籍比較常見的是非侵入式的,它的實現完全放在智能指針模板類內。
模板類有一個用于保存資源類對象的指針變量和一個用于記錄資源對象引用計數的指針變量。
兩者是所有的智能指針對象共享的,所以通過指針保存。
?
侵入式則不同,它的實現分散在智能指針模板和使用資源對象類中:
模板類只有一個用于保存資源對象的指針變量,資源對象的引用計數卻放在資源對象類中。
?
非侵入式智能指針,它的引用計數變量為了保證所有對象共享,需要用堆里的內存。
因此需要用new,其實這點兩者都一樣,不一樣的是使用new的次數。
侵入式智能指針的引用計數變量保存在資源對象內,因為對象是唯一的,所以引用計數也是唯一的。
相比非侵入式智能指針,侵入式智能指針的利弊:
優點:
1> 一個資源對象無論被多少個侵入式智能指針包含,從始至終只有一個引用計數變量。
不需要在每一個使用智能指針對象的地方都new一個計數對象,這樣子效率比較高,使用內存也比較少,且比較安全;
2> 因為引用計數存儲在資源對象本身,所以在函數調用的時候可以直接傳遞資源對象地址,而不用擔心引用計數值丟失。
(非侵入式智能指針對象的拷貝,必須帶著智能指針模板,否則就會出現對象引用計數丟失)。
缺點:
1> 資源對象類必須有引用計數變量,并且該變量的增減允許被侵入式智能指針模板類操作。
2> 如果該資源類對象并不沒有必要使用智能指針時,它還是會帶著引用計數變量。
【2】侵入式智能指針實現
1>實現代碼如下:
1 #include <iostream> 2 using namespace std; 3 4 template< class T > 5 class smartPtr 6 { 7 public: 8 smartPtr(T* ptr) 9 { 10 m_ptr = ptr; 11 if (m_ptr != NULL) 12 m_ptr->AddRef(); 13 } 14 smartPtr(const smartPtr<T>& spObj) 15 { 16 m_ptr = spObj.m_ptr; 17 if (m_ptr) 18 m_ptr->AddRef(); 19 } 20 ~smartPtr() 21 { 22 if (m_ptr != NULL) 23 { 24 m_ptr->Release(); 25 m_ptr = NULL; 26 } 27 } 28 29 T* operator->() const 30 { 31 return m_ptr; 32 } 33 34 T* Get() const 35 { 36 return m_ptr; 37 } 38 private: 39 T* m_ptr; 40 }; 41 42 43 class Int 44 { 45 public: 46 Int(int value) : m_nValue(value) 47 { 48 m_pCount = new int(0); 49 std::cout <<"Construct: "<<this<<std::endl; 50 } 51 52 ~Int() 53 { 54 std::cout <<"Destruct: "<<this<<std::endl; 55 } 56 57 void AddRef() 58 { 59 (*m_pCount)++; 60 } 61 62 void Release() 63 { 64 --(*m_pCount); 65 if ((*m_pCount) == 0) 66 { 67 delete this; 68 } 69 } 70 71 int GetCount() 72 { 73 return (*m_pCount); 74 } 75 76 private: 77 int* m_pCount; 78 int m_nValue; 79 }; 80 81 void TestTwo(Int* ptr) 82 { 83 smartPtr<Int> spTemp = ptr; 84 std::cout<<spTemp->GetCount()<<" "<<spTemp.Get()<<std::endl; //計數為2 85 smartPtr<Int> spObj = spTemp; 86 std::cout<<spObj->GetCount()<<" "<<spTemp.Get()<<std::endl; //計數為3 87 } 88 89 void TestOne() 90 { 91 Int* pInt = new Int(10); 92 smartPtr<Int> spInt = pInt; 93 std::cout<<spInt->GetCount()<<" "<<spInt.Get()<<std::endl; //計數為1 94 TestTwo(pInt); 95 std::cout<<spInt->GetCount()<<" "<<spInt.Get()<<std::endl; //計數為1 96 } 97 98 void main() 99 { 100 TestOne(); 101 } 102 103 //執行結果如下: 104 /* 105 Construct: 009749E0 106 1 009749E0 107 2 009749E0 108 3 009749E0 109 1 009749E0 110 Destruct: 009749E0 111 */以上為不完整代碼實現,僅僅為了理解侵入式智能指針而已。
?
Good Good Study, Day Day Up.
順序? 選擇? 循環 總結
轉載于:https://www.cnblogs.com/Braveliu/p/3300235.html
總結
以上是生活随笔為你收集整理的资源共享型智能指针实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jacoco统计server端功能测试覆
- 下一篇: winform 以不规则图形背景显示窗体