[英]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.