我在使用 std::weak_ptr
和 std::make_shared
时偶然发现了这种行为,我发现它有点奇怪。我正在使用 C++11。
#include <iostream>
#include <memory>
int main()
{
std::weak_ptr<int> weak;
std::shared_ptr<int> shared {std::make_shared<int>(42)};
weak = shared;
std::cout << "Meaning of life: " << *weak.lock() << std::endl;
weak = std::make_shared<int>(23);
std::cout << "Meaning of life: " << *weak.lock() << std::endl;
return 0;
}
第一个 std::cout
打印正常,第二个给我一个段错误。我尝试在 cppreference 上查看 std::weak_ptr
和 std::shared_ptr
的页面但我仍然不明白为什么会这样。必须创建一个临时对象让我觉得很麻烦,这是在 C++14 中已经解决的问题还是我没有看到的东西?
谢谢!
最佳答案
weak_ptr
只有在仍然存在指向同一个底层对象的 shared_ptr
对象时才能在锁定后解除引用。
在你的第一部分
std::shared_ptr<int> shared {std::make_shared<int>(42)};
weak = shared;
std::cout << "Meaning of life: " << *weak.lock() << std::endl;
确实如此。在第二部分
weak = std::make_shared<int>(23);
std::cout << "Meaning of life: " << *weak.lock() << std::endl;
事实并非如此,因为 shared_ptr
是一个临时对象。
您在这里遇到的正是 weak_ptr
的构建目的——只有在其他一些 shared_ptr
指向同一个底层对象时它才有效。那是its purpose :
std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr... If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
关于c++11 - 使用 std::make_shared 分配 std::weak_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282893/