c++11 - 使用 std::make_shared 分配 std::weak_ptr

标签 c++11 weak-ptr make-shared

我在使用 std::weak_ptrstd::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_ptrstd::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/

相关文章:

C++11 原子。为什么这个编译,而不是链接?

c++ - 你如何通过传递 "this"关键字来分配 weak_ptr?

c++ - weak-ptr 变为 null,应用程序每周崩溃 1 次

c++ - 我可以将 boost::make_shared 与私有(private)构造函数一起使用吗?

c++ - 该代码段中是否会发生死锁,为什么?

c++ - 如何在 C++ 程序中获取当前日期?

c++ - std::swap 是否保证通过 ADL 找到非成员交换?

c++ - 是否存在无法锁定(提升为 shared_ptr)的 weak_ptr 之类的东西?如果不是,为什么?

C++ 为类模板提供初始化列表构造函数

c++ - 在什么意义上 weak_ptr 'own' 是 shared_ptr?