日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

资源共享型智能指针实现方式

發布時間:2023/12/18 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 资源共享型智能指针实现方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【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

總結

以上是生活随笔為你收集整理的资源共享型智能指针实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。