c++ - 为什么共享指针不删除内存?

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

shared_ptr<string> pNico(new string("Nico"));
shared_ptr<string> pJutta(new string("Jutta"));
// put them multiple times in a container
vector<shared_ptr<string>> whoMadeCoffee;
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);

pNico = nullptr;         
whoMadeCoffee.resize(2);

At the end of the program, when the last owner of the string gets destroyed, the shared pointer calls delete for the object it refers to. Such a deletion does not necessarily have to happen at the end of the scope. For example, assigning the nullptr to pNico or resizing the vector so that it contains only the first two element s would delete the last owner of the string initialized with nico .

(来自 Josuttis,Nicolai M..“C++ 标准库。”)

我的问题是,为什么在上述情况下不能保证 "Nico" 对象的内存会在作用域末尾被删除?

虽然如果我们改为这样做

whoMadeCoffee.resize(2);
pNico = nullptr;

“Nico”相关的内存确实被删除了。

有人可以解释一下区别吗?

最佳答案

At the end of the program, when the last owner of the string gets destroyed, the shared pointer calls delete for the object it refers to. Such a deletion does not necessarily have to happen at the end of the scope.

string("Nico") 将在引用计数达到 0 时被销毁。在您的示例中,它甚至在到达范围末尾之前就达到 0(对于 Nico)。

如果您与当前范围之外的其他人共享,例如有一个返回 shared_ptr 的函数,或者这是一个更简单的示例,它可能会超出其范围:

shared_ptr<string> pNico0(new string(""));
{ 
    shared_ptr<string> pNico1(new string("Nico"));
    pNico0 = pNico1; // pNico0 reference count = 2
}
// pNico0 reference count = 1

住在 godbolt

关于c++ - 为什么共享指针不删除内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223611/

相关文章:

c++ - 浴室同步和线程队列

c++ - 如何在 boost 正则表达式中指定 } (右大括号)?

c++ - 我是否必须使用 weak_ptr.lock() 来测试它是否指向有效对象?

C++:在函数中使用共享指针作为参数是否可以,还是在浪费内存?

使用 bool 和 const char 的 C++ 函数重载会产生歧义而不发出警告 (MSVC2012)

c++ - 使用 Boost 属性树将 Unicode 字符串写入 XML

c++ - 如何在 C++11 中创建指向静态成员函数的指针映射?

c++ - 将 16 字节 CAS 与 GCC 结合使用时出现未定义的引用链接器错误

c++ - 转发 decltype 检测 - C++ 11

c++ - vector<A> vs vector<A*> vs vector<shared_ptr<A>> 在 C++ 中