Search code examples
c++stlauto-ptr

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.


Solution

  • 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.