简体   繁体   中英

How to effectively delete C++ objects stored in multiple containers? auto_ptr?

I have an application which creates objects of a certain kind (let's say, of "Foo" class) during execution, to track some statistics, and insert them into one or both of two STL maps, say:

map<Foo*, int> map1;
map<Foo*, int> map2;

I was wondering what is the best way to delete the Foo objects. At the moment my solution is to iterate over map1 and map2, and put the Foo pointers into a set, then interating on this set and call delete on each.

Is there a more effective way, possibly using auto_ptr? If so how, since auto_ptr<> objects can't be stored in STL containers?

Thanks in advance.

auto_ptr objects cannot, as you say, be stored in STL containers. I like to use the shared_ptr object (from boost) for this purpose. It is a referenced counted pointer, so the object will be deleted once only, when it goes out of scope.

typedef<shared_ptr<Foo>, int> Map;
Map map1;
Map map2;

Now, you just add and remove from map1 and map2 , shared_ptr objects as they were pointers, and they will take care of the deletion, when the last reference is removed.

Use boost::shared_ptr - it's specifically intended for cases where the object can be referenced from multiple locations. Using auto_ptr is not an option here - once the first auto_ptr to an object is destroyde the second one is left with a dangling pointer and that's direct way to undefined behaviour.

I guess you need a master list or set of objects, either held by value if you can afford to copy them, or more likely held by pointer so you can copy the pointer and put them into other collections.

std::list<Foo*> Master;

These other collections ( map1 and map2 in your example) can have these pointers inserted and removed at any time. When finally you want to delete everything, you can probably just delete the maps, or let them go out of scope, or ignore them, and just once, go back to the master list and iterate through that deleting the pointers that are found.

http://ootips.org/yonat/4dev/smart-pointers.html talks about certain kinds of smart pointers that may be storeable in STL containers. See here

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