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);