C++智能指針shared_ptr分析
C++智能指針shared_ptr分析
概要:
shared_ptr是c++智能指針中適用場景多,功能實(shí)現(xiàn)較多的智能指針。它采取引用計(jì)數(shù)的方法來實(shí)現(xiàn)釋放指針?biāo)赶虻馁Y源。下面是我代碼實(shí)現(xiàn)的基本功能。
實(shí)例代碼:
template<class T> class sharedptr { public: sharedptr(T* ptr) :_ptr(ptr) , _refCount(new int(1)) {} sharedptr(sharedptr<T>& sp) :_ptr(sp._ptr) , _refCount(sp._refCount) { ++(*_refCount); } sharedptr& operator = (sharedptr<T>& sp) //現(xiàn)代寫法 { swap(_ptr, sp._ptr); swap(_refCount, sp._refCount); return *this; } /*sharedptr& operator = (sharedptr<T>& sp) { if (this != &sp) { this->Release(); _ptr = sp._ptr; _refCount = sp._refCount; ++(*_refCount); } return *this; }*/ void Release() { if (--(*_refCount) == 0) { delete _ptr; delete _refCount; } } ~sharedptr() { Release(); } private: T* _ptr; int* _refCount; };
但是呢這只能刪除基本類型,例int、double類型指針。但對于數(shù)組指針不是適用。在c++中動態(tài)內(nèi)存管理中,new/delete對應(yīng),new[]/delete[]對應(yīng),所以就引入了定制刪除器這個(gè)概念。
定制刪除器基本的實(shí)現(xiàn)就是:
template<class T> struct Delete { void operator()(T* ptr) { delete ptr; } }; template<class T> struct DeleteArray { void operator()(T* ptr) { delete[] ptr; } };
如何在shared_ptr中使用呢,下來我用代碼簡單做個(gè)示范。
template<class T> //定制刪除器 struct Delete { void operator()(T* ptr) { delete ptr; } }; template<class T>//定制刪除器 struct DeleteArray { void operator()(T* ptr) { delete[] ptr; } }; template<class T, class D = Delete<T>> class sharedptr { public: sharedptr(T* ptr, D del) :_ptr(ptr) , _refCount(new int(1)) , _del(del) {} sharedptr(sharedptr<T>& sp) :_ptr(sp._ptr) , _refCount(sp._refCount) { ++(*_refCount); } sharedptr& operator = (sharedptr<T>& sp) //現(xiàn)代寫法 { swap(_ptr, sp._ptr); swap(_refCount, sp._refCount); return *this; } /*sharedptr& operator = (sharedptr<T>& sp) { if (this != &sp) { this->Release(); _ptr = sp._ptr; _refCount = sp._refCount; ++(*_refCount); } return *this; }*/ void Release() { if (--(*_refCount) == 0) { printf("delete:0x%p\n", _ptr); _del(_ptr); delete _refCount; } } ~sharedptr() { Release(); } private: T* _ptr; int* _refCount; D _del; };
在調(diào)用時(shí),應(yīng)這樣寫調(diào)用函數(shù):
void TextSharedptr() { DeleteArray<int> da; sharedptr<int, DeleteArray<int>> sp(new int[3], da); }
而weak_ptr弱引用智能指針是通過(引用不增加計(jì)數(shù))來打破循環(huán)引用的;
什么循環(huán)引用,這可以簡單用一個(gè)雙向鏈表來解釋:
而weak_ptr通過只引用不增加計(jì)數(shù)的方法打破了循環(huán)引用這個(gè)問題。但在使用weak_ptr的前提是確定在使用shared_ptr智能指針時(shí)存在循環(huán)引用這個(gè)問題。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
OpenCV實(shí)現(xiàn)圖像角點(diǎn)檢測
這篇文章主要為大家詳細(xì)介紹了OpenCV實(shí)現(xiàn)圖像角點(diǎn)檢測,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01C語言實(shí)現(xiàn)系統(tǒng)關(guān)機(jī)注銷功能
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)系統(tǒng)關(guān)機(jī)注銷功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02C++ 中類對象類型的轉(zhuǎn)化的實(shí)例詳解
這篇文章主要介紹了C++ 中類對象類型的轉(zhuǎn)化的實(shí)例詳解的相關(guān)資料,這里提供實(shí)例幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08C語言代碼實(shí)現(xiàn)點(diǎn)餐系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)點(diǎn)餐系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07