Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 std::弱\u ptr分配与std::使\u共享_C++11_Weak Ptr_Make Shared - Fatal编程技术网

C++11 std::弱\u ptr分配与std::使\u共享

C++11 std::弱\u ptr分配与std::使\u共享,c++11,weak-ptr,make-shared,C++11,Weak Ptr,Make Shared,我在使用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::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;
}
#包括
#包括
int main()
{
标准::弱\u ptr弱;
std::shared_ptr shared{std::make_shared(42)};
弱=共享;

std::cout只有当指向同一底层对象的
共享\u ptr
对象仍然存在时,才能在锁定后解除对
弱\u ptr
的引用

在你的第一部分

std::shared_ptr<int> shared {std::make_shared<int>(42)};
weak = shared;
std::cout << "Meaning of life: " << *weak.lock() << std::endl;
std::shared_ptr shared{std::make_shared(42)};
弱=共享;

std::cout这是因为您创建了一个临时共享指针,并立即将其分配给此行中的弱指针:

weak = std::make_shared<int>(23);
weak=std::使_共享(23);
赋值运算符结束后,临时共享指针被销毁,引用计数达到0(因为弱指针不会增加引用计数器),因此,堆上的资源被删除

weak = std::make_shared<int>(23);