Re: What is the best way to clear a std::set containing dynamically allocated pointers?
Olivier Langlois ha scritto:
Hi,
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?
Normally with any other containers, I would just traverse it to delete
all the elements and then call clear() on the container. However, you
cannot do it for set (I think), because the elements are the key as
well and you don't want the set custom comparator function to access
freed memory.
I have came up with
while( !s.empty() )
{
p = s.begin();
s.erase(s.begin());
delete p;
}
but this feel clumpsy. I am seeking this group wisdom to figure out if
there would be a better way.
Just use boost::ptr_set instead of std::set and let the container call
delete for you on every pointer. See
http://boost.org/libs/ptr_container/doc/ptr_container.html for details.
In C++0x we will have a "standard" alternative, which will be
std::set<std::unique_ptr<T>>.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]