Re: What is the best way to clear a std::set containing dynamically allocated pointers?
On Nov 13, 6:16 pm, Olivier Langlois <olangl...@sympatico.ca> wrote:
Without using boost::smart_ptr because the pointers ownership is not
fuzzy (ie: when it is time to clear the set, it is safe to delete all
its contained pointers), what is the best way to do it?
Fuzzy ownership is only one use case for boost::shared_ptr (which I've
never encountered). It helps in your case as well.
Normally with any other containers, I would just traverse it to delete
all the elements and then call clear() on the container.
As became evident from the replies so far, there is no clear solution
to keeping plain pointers in containers. You haven't mentioned the
following case, but I think it is a problem of yours:
void foo()
{
MySet mySet = makeSet(/* ... */);
useSet(mySet);
// you will not get here if there was an exception
deletePointers(mySet);
}
There is no guarantee that you will get to the traversal code.
What you need is to change your typedefs:
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<MyClass> MyClassPtr;
typedef std::set<MyClassPtr,CompFuncThatDerefencePointers> MySet;
Now your problems have magically vanished. :)
Ali
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]