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 混淆

php - 通过Qt发送POST缩小帖子内容

c++ - 使用 **ClassObject ( C++ ) 调用公共(public)成员

c++ - 将 std::shared_ptr 转换为 QPointer

c++ - 使用 shared_ptr

C++基本指针问题

c++ - 通过将文本文件发送到stdin,在Visual Studio中自动测试C++控制台应用程序?

c++ - std::containers 的日志分配器?

c++ - 你如何使用 std::not1 和 std::not2?

c++ - 递归尾随返回类型?