C++中各种智能指针的实现及弊端(五)
生活随笔
收集整理的這篇文章主要介紹了
C++中各种智能指针的实现及弊端(五)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++中各種智能指針的實現及弊端(五)
文章目錄
- C++中各種智能指針的實現及弊端(五)
- 一、std::shared_ptr的循環引用
- **二、循環引用分析:**
- 三、解決方法:
- 四、weak_ptr解決的原理(圖片中詳細內容)
- 五、上面所有的智能指針都沒有寫刪除器,因為其所管理的資源不都是new出來的,所以得寫一個刪除器**
- 六、C++11和boost中智能指針的關系**
一、std::shared_ptr的循環引用
struct ListNode {int _data;shared_ptr<ListNode> _prev;shared_ptr<ListNode> _next;~ListNode(){ cout << "~ListNode()" << endl; } };int main() {shared_ptr<ListNode> node1(new ListNode);shared_ptr<ListNode> node2(new ListNode);cout << node1.use_count() << endl;cout << node2.use_count() << endl;node1->_next = node2;node2->_prev = node1;cout << node1.use_count() << endl;cout << node2.use_count() << endl;return 0; }上面的代碼出現的問題是資源泄漏,因為node1和node2都沒有釋放掉;
二、循環引用分析:
三、解決方法:
采用weak_ptr來解決循環引用問題;
四、weak_ptr解決的原理(圖片中詳細內容)
五、上面所有的智能指針都沒有寫刪除器,因為其所管理的資源不都是new出來的,所以得寫一個刪除器**
// 仿函數的刪除器 template<class T> struct FreeFunc {void operator()(T* ptr){cout << "free:" << ptr << endl;free(ptr);} };template<class T> struct DeleteArrayFunc {void operator()(T* ptr){cout << "delete[]" << ptr << endl;delete[] ptr;} };int main() {FreeFunc<int> freeFunc;shared_ptr<int> sp1((int*)malloc(4), freeFunc);DeleteArrayFunc<int> deleteArrayFunc;shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);return 0; }六、C++11和boost中智能指針的關系**
總結
以上是生活随笔為你收集整理的C++中各种智能指针的实现及弊端(五)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++中各种智能指针的实现及弊端(三)
- 下一篇: C++中各种智能指针的实现及弊端(四)