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 withnico
.
(来自 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/