how to free memory from a set

后端 未结 3 1736
庸人自扰
庸人自扰 2021-01-24 16:46

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 p

3条回答
  •  不思量自难忘°
    2021-01-24 17:10

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

提交回复
热议问题