智能指针引用计数器版
生活随笔
收集整理的這篇文章主要介紹了
智能指针引用计数器版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前些日子,寫過一個普通的智能指針,模擬的是boost中的auto_ptr,今天又寫了一個關于boost中的share_ptr,引用計數器智能指針,感覺還行,功能基本實現,設計思想基本上是這么一回事,智能指針類管理資源,引用計數器類管理是否有多個智能指針指向同一個資源,如果有為這個資源設一個引用計數器,計數器值表示有多少個智能指針在使用這個資源,一旦有一個智能指針準備釋放這個資源,僅僅對計數器減一,只有當沒有智能指針指向這個資源,才真正的釋放資源,當然你也可以強制讓所有的智能指針釋放這個資源,直接delete掉資源,然后將所有的智能指針delete掉。
下面是我代碼:
#include <iostream>using namespace std;class Test { private:int n; public:Test(int m):n(m){}~Test(){ cout<<"Test destructor function is called\n"; }void get(){ cout<<"Test get() is called\n"; } };class CountPtr { public:Test* ptr;int usecount; public:CountPtr(Test* p):ptr(p){usecount = 1;cout<<"CountPtr constructor function is called\n";}~CountPtr(){ cout<<"CountPtr destructor function is called\n"; delete ptr; }};class SmartPtr { private:CountPtr* ptr; public:SmartPtr(Test* p){ cout<<"SmartPtr constructor function is called\n";ptr = new CountPtr(p);}~SmartPtr(){ptr->usecount--;if(ptr->usecount == 0) //只有所有的智能指針都釋放資源,才能將資源delete掉{cout<<"SmartPtr destructor function is called\n";delete ptr;}}SmartPtr(const SmartPtr& p) //智能指針拷貝構造函數,因為有了拷貝構造函數才使其他的智能指針才能共享資源,不過這個是針對淺拷貝,深拷貝可以無視{cout<<"SmartPtr copy constructor function is called\n";ptr = p.ptr;ptr->usecount++;}SmartPtr& operator=(const SmartPtr& p) //智能指針賦值構造函數,因為有了賦值構造函數才使其他的智能指針才能共享資源,不過這個是針對淺拷貝,深拷貝可以無視{cout<<"SmartPtr assign constructor function is called\n";if(this == &p)return *this;ptr->usecount--;if(ptr->usecount == 0){delete ptr;ptr = NULL;}ptr = p.ptr;return *this;}Test* operator->(){ return ptr->ptr;} };int main() {{SmartPtr ptr(new Test(8));ptr->get();SmartPtr p1 = ptr;SmartPtr p2(new Test(7));p2 = ptr; }return 0; }?
轉載于:https://www.cnblogs.com/GODYCA/archive/2013/01/19/2868112.html
總結
以上是生活随笔為你收集整理的智能指针引用计数器版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WP8模拟器启动失败解决方法
- 下一篇: 基金成立的时间长好还是短好 根据实际情