puccio
puccio

Reputation: 3144

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.

Upvotes: 1

Views: 952

Answers (4)

quamrana
quamrana

Reputation: 39354

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.

Upvotes: 3

Preet Sangha
Preet Sangha

Reputation: 65476

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

Upvotes: 1

1800 INFORMATION
1800 INFORMATION

Reputation: 135255

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.

Upvotes: 10

sharptooth
sharptooth

Reputation: 170469

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.

Upvotes: 7

Related Questions