问题描述
我意识到,调用包含共享指针的vector.clear()
之后,shared_ptr
拥有的对象的析构函数不会被释放.
I realized that after calling vector.clear()
which hold shared pointers, the destructors of the object which own by shared_ptr
is not being released.
代码示例可以在下面看到.甚至vector.clear()
被调用,共享指针之后的析构函数调用也超出了范围.我的问题是-我是否必须通过重置手动删除向量中的所有智能指针?有什么更简单的建议方法吗?
Code example can be seen below . Even vector.clear()
being called, destructor called after shared pointer goes beyond the scope.My question is - do I have to delete all smart pointers inside the vector manually by resetting them? Is there any easier way that you can advice ?
Output :
constructor
I am here
destructor
Code:
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
A(){cout << "constructor" << endl;};
~A(){cout << "destructor" << endl;};
};
int main( )
{
shared_ptr<A> sharedptr (new A);
std::vector<shared_ptr<A> > test;
test.push_back(sharedptr);
test.clear();
cout << "I am here" << endl;
}
推荐答案
在这种情况下,您有两个shared_ptr<A>
副本,一个是sharedptr
变量,另一个是向量中的元素.
you have two copies of shared_ptr<A>
in this case, one is the sharedptr
variable and the other as an element in the vector.
改为执行此操作
test.push_back(std::move(sharedptr));
现在请注意原始的sharedptr
已在内部移动并且不再可用.另一件事是什么也不做,这是shared_ptr的完全有效用法,sharedptr
在超出范围后会自行清理.
note now the original sharedptr
has it's internal moved and no longer usable. The other thing is don't do anything at all, this is a perfectly valid usage of of shared_ptr and sharedptr
will clean up itself after it goes out of scope.
这篇关于共享指针的向量,清除向量后出现内存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!