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++ - Qt::UniqueConnection 是如何工作的?

c++ - 找不到 MSVCP110D.dll

c++ - 构造期间对 vector 中元素的引用

c++ - C++,Shared_ptr,请告诉我为什么我的代码给出错误?

c++ - std shared_pointer_cast 未定义

c++ - 单位球体 C++ 上 N 个相互排斥点的蒙特卡罗(可能是模拟退火?)方法

c++ - val != std::numeric_limits<double>::infinity() 或 !isinf(val) 或 isfinite(val)

c++ - 模板调用彼此的功能

c++ - shared_ptr 的原始指针构造函数是错误的吗?

c++ - shared_ptr 与 scoped_ptr