国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

智能指針shared_ptr的用法

2019-11-11 02:13:50
字體:
來源:轉載
供稿:網友

智能指針shared_ptr的用法

2016-12-03 15:39 by jiayayao, 360 閱讀, 0 評論, 收藏, 編輯

  為了解決C++內存泄漏的問題,C++11引入了智能指針(Smart Pointer)。

  智能指針的原理是,接受一個申請好的內存地址,構造一個保存在棧上的智能指針對象,當程序退出棧的作用域范圍后,由于棧上的變量自動被銷毀,智能指針內部保存的內存也就被釋放掉了(除非將智能指針保存起來)。

  C++11提供了三種智能指針:std::shared_ptr, std::unique_ptr, std::weak_ptr,使用時需添加頭文件<memory>:

      #include <memory>

  shared_ptr使用引用計數,每一個shared_ptr的拷貝都指向相同的內存。每使用他一次,內部的引用計數加1,每析構一次,內部的引用計數減1,減為0時,刪除所指向的堆內存。

shared_ptr的基本用法初始化

  可以通過構造函數、std::make_shared<T>輔助函數和reset方法來初始化shared_ptr:

    std::shared_ptr<int> p(new int(1));    std::shared_ptr<int> p2 = p;    std::shared_ptr<int> p3 = std::make_shared<int>(5);    std::shared_ptr<int> ptr;    ptr.reset(new int(1));    if (ptr) {        cout << "ptr is not null";    }

   注意,不能將一個原始指針直接賦值給一個智能指針,如下所示,原因是一個是類,一個是指針。

    std::shared_ptr<int> p4 = new int(1);// error

  當智能指針中有值的時候,調用reset會使引用計數減1.

獲取原始指針  
    std::shared_ptr<int> p4(new int(5));    int *pInt = p4.get();指定刪除器

  智能指針可以指定刪除器,當智能指針的引用計數為0時,自動調用指定的刪除器來釋放內存。std::shared_ptr可以指定刪除器的一個原因是其默認刪除器不支持數組對象,這一點需要注意。

  2. 使用shared_ptr需要注意的問題

  但凡一些高級的用法,使用時都有不少陷阱。

不要用一個原始指針初始化多個shared_ptr,原因在于,會造成二次銷毀,如下所示:
    int *p5 = new int;    std::shared_ptr<int> p6(p5);    std::shared_ptr<int> p7(p5);// logic error不要在函數實參中創建shared_ptr。因為C++的函數參數的計算順序在不同的編譯器下是不同的。正確的做法是先創建好,然后再傳入。
    function(shared_ptr<int>(new int), g());禁止通過shared_from_this()返回this指針,這樣做可能也會造成二次析構。避免循環引用。智能指針最大的一個陷阱是循環引用,循環引用會導致內存泄漏。解決方法是AStruct或BStruct改為weak_ptr。
struct AStruct;struct BStruct;struct AStruct {    std::shared_ptr<BStruct> bPtr;    ~AStruct() { cout << "AStruct is deleted!"<<endl; }};struct BStruct {    std::shared_ptr<AStruct> APtr;    ~BStruct() { cout << "BStruct is deleted!" << endl; }};void TestLooPReference(){    std::shared_ptr<AStruct> ap(new AStruct);    std::shared_ptr<BStruct> bp(new BStruct);    ap->bPtr = bp;    bp->APtr = ap;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东莞市| 什邡市| 阿巴嘎旗| 三台县| 潢川县| 郯城县| 扎兰屯市| 宣恩县| 河北省| 瓦房店市| 江达县| 孙吴县| 蒙阴县| 六盘水市| 呼和浩特市| 沙湾县| 屏南县| 江孜县| 永胜县| 东乡县| 桐乡市| 囊谦县| 新余市| 田阳县| 漠河县| 金湖县| 信丰县| 乡宁县| 仁布县| 惠东县| 海口市| 长宁县| 乌什县| 黄陵县| 临沂市| 余庆县| 阜平县| 博乐市| 玛曲县| 桓台县| 越西县|