简体   繁体   中英

std::list.remove is calling the destructor but doesn't delete it

I am having a problem with 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; 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. You must manually find the item and delete it before removing it.

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. The unique_ptr will call delete on the managed object for you.

Or if you're using a pre-C++11 compiler, boost::ptr_list is another option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM