簡體   English   中英

在C ++中使用shared_ptr的指針的意外行為

[英]Unexpected behavior of pointer to pointer using shared_ptr in C++

使用智能指針時,C ++中的指針行為使我感到困惑。

在下面的可編譯代碼示例中,您可以看到重新分配原始指針pA會影響指向指針ppA的指針,但是使用std::shared_ptr時並非如此。 這似乎很違反直覺。

#include <iostream>
#include <memory>

using namespace std;

int main() {

    // compare the functionality of raw and smart pointers
    int* pA = new int(1);
    int* pB = new int(2);
    shared_ptr<int> pAsmart(new int(1));
    shared_ptr<int> pBsmart(new int(2));

    // pointer to a pointer
    int** ppA = &pA;
    shared_ptr< shared_ptr<int> > ppAsmart = make_shared< shared_ptr<int> >(pA);

    cout << **ppA << endl; // prints 1
    cout << **ppAsmart << endl; // prints 1

    pA = pB;
    pAsmart = pBsmart;

    cout << **ppA << endl; // prints 2
    cout << **ppAsmart << endl; // prints 1 (huh?)


}

shared_ptr<shared_ptr>與指針指向的指針不同。 ppAsmart保留make_shared()返回的原始shared_ptr 您沒有做任何事情來使ppAsmart指向其他任何東西,因此它仍然持有仍然指向原始pA對象(其值為1)的shared_ptr<int> 。創建ppAsmart ,您需要重新分配pA使其指向原始pB對象的值為2,而ppA仍指向pA變量,因此取消引用ppA會得到值為2的原始pB對象。但是ppAsmart仍指向值為1的原始pA對象。並不像ppA那樣指向pA變量本身。

ppAsmart指向一個新對象,該對象指向pA的對象; 特別是它並不指向pA 它保持不變。 嘗試用指針和尖的對象描繪一個圖,您將看到。

shared_ptr< shared_ptr<int> > ppAsmart = make_shared< shared_ptr<int> >(pA);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM