how to free memory from a set

2019-03-01 05:56发布

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 I still get memory leaks because the allocated memory stays uncleared for some reason.

3条回答
女痞
2楼-- · 2019-03-01 06:20

Set only clears what it allocates itself. If you allocate something yourself, you'll have to clear it yourself.

查看更多
3楼-- · 2019-03-01 06:25

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.

查看更多
Rolldiameter
4楼-- · 2019-03-01 06:36

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

查看更多
登录 后发表回答