hey, i got a set that includes pointers to an allocated memory, i am using the clear method forexample : setname.clear();
and the set itself is getting cleared and his pointers but still i got memoryleaks the allocated memory stays uncleared for some reason.
thanks in advance for your answer.
views:
63answers:
3
+3
A:
Set only clears what it allocates itself. If you allocate something yourself, you'll have to clear it yourself.
yorick
2010-09-23 14:03:02
+2
A:
Clear()
only removes the pointers not the object it points to. You'll have either to iterate on each object before removing it to delete
it, or use something like std::tr1::shared_ptr
(also in Boost).
Wernight
2010-09-23 14:03:21
+5
A:
std::set's clear() method does remove elements from the set. However, in your case set contains pointers that are being removed, but the memory they point to is not released. You have to do it manually before the call to clear()
, for example:
struct Deleter
{
template <typename T>
void operator () (T *ptr)
{
delete ptr;
}
};
for_each (myset.begin (), myset.end (), Deleter());
There is a library in Boost called Pointer Container that solves this problem.
Vlad Lazarenko
2010-09-23 14:05:29
Or, if Boost is available, try making it a set of boost::shared_ptr<ElementType> (from Boost.SmartPtr: http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/smart_ptr.htm). TR1 has smart_ptr as well, I believe.
gregg
2010-09-23 14:15:54
shared_ptr would be a great overhead if pointer is not really shared, but just resides in the set (to avoid copying, for example). This was exactly one of the motivations to to create ptr_container.
Vlad Lazarenko
2010-09-23 14:23:55