[英]std::list.remove is calling the destructor but doesn't delete it
I am having a problem with std::list. 我对std :: list有问题。
std::list<Component*> mComponents;
//add some pointer in it
Component * comp = getComponent("positionComponent");
mComponents.remove(comp);
For some reason, it calls the destructor of the comp pointer but doesn't delete it; 由于某种原因,它会调用comp指针的析构函数,但不会删除它。 items that are removed through destructor gets removed, while all the other items in the list kept intact.
通过析构函数删除的项目将被删除,而列表中的所有其他项目保持不变。 What can cause this behavior?
什么会导致这种行为?
Calling list.remove
does call the destructor of the contained type, but in your case, the destructor for Component *
is being called, which is a no-op. 调用
list.remove
确实会调用所包含类型的析构函数,但是在您的情况下,将调用Component *
的析构函数,这是一个空操作。 You must manually find the item and delete
it before removing it. 您必须手动找到该项目并将其
delete
,然后再将其删除。
auto item = std::find(mComponents.begin(), mComponents.end(), comp);
if(item != mComponents.end()) {
delete *item;
mComponents.remove(item);
}
This is the reason why it is not advisable to stick raw pointers in standard containers. 这就是为什么不建议将原始指针粘贴在标准容器中的原因。 You should use
std::list<std::unique_ptr<Component>>
instead. 您应该使用
std::list<std::unique_ptr<Component>>
。 The unique_ptr
will call delete
on the managed object for you. unique_ptr
将为您调用托管对象上的delete
。
Or if you're using a pre-C++11 compiler, boost::ptr_list
is another option. 或者,如果您使用的是C ++ 11之前的编译器,则
boost::ptr_list
是另一个选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.