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

Why does the shared pointer does not delete memory?

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.. "The C++ Standard Library.")

我的问题是为什么在上述情况下不能保证 "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)。

如果您与当前范围之外的其他人共享,例如具有 returns 和 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