c++ make_shared & shared_ptr 小結(jié)

由于項目需求需要使用c++, 特意寫點學(xué)習(xí)筆記, 以下例子均來自網(wǎng)友分享的
資料, 如果原作者覺得有損您的利益, 請通知本人進(jìn)行刪除.

make_shared & shared_ptr

typedef struct _StructA StructA;
typedef struct _StructB StructB;

struct _StructA
{
    int i;
    std::shared_ptr<StructB> pStructB;
    _StructA(): i(int())
    {
        printf("_StructA alloc \n");
    };
    
    ~_StructA()
    {
        printf("_StructA dealloc \n");
    };
} ;

struct _StructB
{
    int i;
    std::shared_ptr<StructA> pStructA;
    _StructB(): i(int())
    {
        printf("_StructB alloc \n");
    };
    
    ~_StructB()
    {
        printf("_StructB dealloc \n");
    };
};
  • make_shared 和 shared_ptr 的用處
// make_shared 和 shared_ptr 設(shè)計初衷是引入引用計數(shù)這個概念來減少程序
// 員的工作量. 他的設(shè)計想法跟 Objective-c 的引用計數(shù)有點類似。請看以下代碼: 

int main(int argc, const char * argv[])
{
    printf("----- start ----- \n");       
    std::shared_ptr<StructA> pA = std::make_shared<StructA>();
    std::shared_ptr<StructB> pB (new StructB());
    printf("----- end ----- \n");
    return 0;
}    

// 打印結(jié)果
**----- start ----- **
**_StructA alloc **
**_StructB alloc **
**----- end ----- **
**_StructB dealloc **
**_StructA dealloc **

通過實驗可以看出, 超出作用域之后就會對 shared_ptr 所作用的對象進(jìn)行引用計數(shù)減少1, 如果發(fā)現(xiàn) shared_ptr 所作用的對象引用計數(shù)為0則說明,這個對象需要釋放內(nèi)存.

  • 環(huán)形引用
    printf("----- start ----- \n");
    std::shared_ptr<StructA> pA = std::make_shared<StructA>();
    std::shared_ptr<StructB> pB = std::make_shared<StructB>();
    pA->pStructB = pB;
    pB->pStructA = pA;
    printf("----- end ----- \n");

// 打印結(jié)果
**----- start ----- **
**_StructA alloc **
**_StructB alloc **
**----- end ----- **

環(huán)形應(yīng)用: 就是對象 A 持有對象 B 的強(qiáng)引用, 對象 B 持有對象 A 的強(qiáng)應(yīng)用,最終導(dǎo)致 A 和 B 都無法釋放。
// 解決方法, 其中一方使用弱引用

struct _StructB
{
    int i;
    // 改為弱引用, 同理針對  StructA 也可以這樣做
    std::weak_ptr<StructA> pStructA;
    // std::shared_ptr<StructA> pStructA;
    _StructB(): i(int())
    {
        printf("_StructB alloc \n");
    };
    
    ~_StructB()
    {
        printf("_StructB dealloc \n");
    };
};
  • make_shared 和 shared_ptr 區(qū)別
   /**
     * 1. 執(zhí)行申請 數(shù)據(jù)體(StructA) 的內(nèi)存申請
     * 2. 執(zhí)行控制塊的內(nèi)存申請
     */
    std::shared_ptr<StructA> pA1(new StructA());
    
    /**
     * 數(shù)據(jù)體 和 控制塊的 內(nèi)存一塊申請
     */
    std::shared_ptr<StructA> pA2 = std::make_shared<StructA>();
  • make_shared 和 shared_ptr 如何選擇
void fun(std::shared_ptr<StructA> pA,  std::shared_ptr<StructB> pB)
{
    printf("pA->i = %d  pB->i = %d \n", pA->i, pB->i);
}

int main(int argc, const char * argv[])
{
    /**
     * 因為C++允許參數(shù)在計算的時候打亂順序,因此可能出現(xiàn)以下順序
     * 1. new StructA
     * 2. new StructB       // 如果在此步出現(xiàn)問題, 那么就會導(dǎo)致 1. 所產(chǎn)生的內(nèi)存無人管理, 造成內(nèi)存泄露
     * 3. shared_ptr A
     * 4. shared_ptr B
     */
    fun(std::shared_ptr<StructA>(new StructA()), std::shared_ptr<StructB>(new StructB()));
    return 0;
}

// 解決方法1
  auto pSA = std::shared_ptr<StructA>(new StructA());
  auto pSB = std::shared_ptr<StructB>(new StructB());
  fun(pSA, pSB);

// 解決方法2
fun(std::make_shared<StructA>(), std::make_shared<StructB>());

. weak_ptr

  1. weak_ptr 主要是用來判斷 shared_ptr 所指向的數(shù)據(jù)內(nèi)存是否存在, 因為make_shared 只作一次內(nèi)存分配, shared_ptr 可以把這種內(nèi)存分配分為兩個步驟, weak_ptr 可以通過 lock 來判斷 shared_ptr 所指向的數(shù)據(jù)內(nèi)存是否被釋放
    std::shared_ptr<StructA> pSA(new StructA());
    std::weak_ptr<StructA> wPSA = pSA;
    pSA.reset(new StructA());
    auto p = wPSA.lock();
    std::cout<< p << std::endl;
    std::cout<< wPSA.use_count() << std::endl;

// 打印結(jié)果
**_StructA alloc **
**_StructA alloc **
**_StructA dealloc **
**0x0**
**0**
**_StructA dealloc **
  • weak_ptr 使用注意
    // 主線程
    std::shared_ptr<StructA> pSA(new StructA());
    std::weak_ptr<StructA> wPSA(pSA);
    
    // 子線程 1
    pSA.reset(new StructA());
    
    // 子線程 2
    // 錯誤做法, 現(xiàn)在編譯器好像也不允許這么做
//    StructA *p = wPSA.get();
//    if ( p )
//    {
//        p->i = 5;
//    }
    
    // 正確做法
    if ( auto p = wPSA.lock() )
    {
        p->i = 5;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容