c++ - 调用 get 后将 shared_ptr 分配给另一个

标签 c++ pointers move shared-ptr move-semantics

shared_ptr<std::string> shared_ptr1 = std::make_shared<std::string>("Foo");
shared_ptr<std::string> shared_ptr2 = std::make_shared<std::string>("Bar"); 

std::string* normal_ptr = shared_ptr1.get(); 
shared_ptr1 = shared_ptr2; 

现在,在“shared_ptr1 = shared_ptr2”赋值之后,第一个字符串“Foo”会被垃圾回收吗?根据this , "Foo"没有被垃圾回收。但我只想确保我遇到的不是未定义的行为。

谢谢!

最佳答案

Now, will the first string "Foo" be garbage collected after the "shared_ptr1 = shared_ptr2" assignment?*

如果你的意思是 std::make_shared<std::string>("Foo") 分配的字符串被摧毁,那么是的。

这意味着normal_ptr , 在你做了 shared_ptr1 = shared_ptr2; 之后指向一个不再存在的对象。

关于c++ - 调用 get 后将 shared_ptr 分配给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56243375/

相关文章:

c++ - 如何计算位图大小?

c - 取消引用结构内的数据 ** 在结构内 *

c - 使用 qsort 对二维数组进行排序时发出警告

Javascript: move 以编程方式创建的图像不起作用

c++ - 如何检查变量是否仍然有效或在其上使用了 std::move?

c++ - 插入排序问题

c++ - 如何在 C++11 之前模拟尾随返回类型中的 decltype?

c++ - xstring第1331行的字符串下标超出范围

对字符串指针数组的打印过程感到困惑

c++ - 将项目从 List move 到 Stack 或 Queue