指向对象的指针列表中的内存泄漏 [英] Memory Leak in a list of pointers to objects
问题描述
我有一个指向对象的指针列表.
I have a list of pointers to objects.
std::list<X*> xList;
我所需要的只是列表的大小,因此我的方法将填充该列表并在其上调用size(),然后返回该大小.
All I need is the size of the list so my method, populates this list and calls size() on it and then returns the size.
注意:我知道这不是最好的解决方案,但是我使用的API提供了动态分配对象的列表,这是我唯一的方法.
NOTE: I know this is not the best solution, but I am using an API that provides a list with dynamically allocated objects and this is the only way I can do it.
现在valgrind表示这里存在内存泄漏.我认为这是因为我从不删除列表中的对象.
Now valgrind is saying that there's memory leaks here. I am assuming that this is because I never delete the objects that are in the list.
我认为我会这样做:
std::list<X*>::iterator iter;
for (iter = xList.begin(); iter != xList.end(); ++iter)
{
delete (*iter);
}
但这是对此的最佳解决方案吗?
but is this the best solution to this?
推荐答案
不,最好的解决方案是改用std::list<std::unique_ptr<X>>
.现在,这些对象将在适当的时候删除它们自己,而您不必担心它.销毁std::list
时,其拥有的X
对象也将销毁.
No, the best solution would be to have a std::list<std::unique_ptr<X>>
instead. Now the objects will delete themselves as and when it's appropriate, and you do not have to concern yourself with it. When the std::list
is destroyed, the X
objects which are owned by it are also destroyed.
这篇关于指向对象的指针列表中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!