gpt4 book ai didi

c++ - 在 C++ 中使用 shared_ptr 指向指针的意外行为

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:53 25 4
gpt4 key购买 nike

在使用智能指针时,我对 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持有原件shared_ptrmake_shared()回。你没有做任何事情来制作 ppAsmart指向其他任何东西,所以它仍然持有 shared_ptr<int>那仍然指向原来的pA对象,其值为 1。创建后 ppAsmart ,然后您将重新分配 pA指向原来的pB对象,其值为 2,ppA仍然指向 pA变量,因此取消引用 ppA给你原来的 pB值为 2 的对象。但是 ppAsmart仍然指向原来的pA值为 1 的对象。它不指向 pA。变量本身,如 ppA是。

关于c++ - 在 C++ 中使用 shared_ptr 指向指针的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com