clearing a vector of pointers

96,082

Solution 1

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

   for (auto p : v)
   {
     delete p;
   } 
   v.clear();

You could avoid the memory management issue altogether by using a std::vector of a suitable smart pointer.

Solution 2

I think the shortest and clearest solution would be:

std::vector<Object*> container = ... ;
for (Object* obj : container)
    delete obj;
container.clear();

Solution 3

You can use for_each :

std::vector<int*> v;

template<typename T>
struct deleter : std::unary_function<const T*, void>
{
  void operator() (const T *ptr) const
  {
    delete ptr;
  }
};

// call deleter for each element , freeing them
std::for_each (v.begin (), v.end (), deleter<int> ());
v.clear ();
Share:
96,082
mahmood
Author by

mahmood

Updated on July 09, 2022

Comments

  • mahmood
    mahmood almost 2 years

    Assume I have defined a class like this:

     class foo {
     private: 
        std::vector< int* > v;
     public:
        ...
        void bar1()
        {
           for (int i = 0; i < 10; i++) {
             int *a = new int;
             v.push_back( a );
           }
        };
    
        void bar2()
        {
           std::vector< int >::iterator it = v.begin();
           for ( ; it != v.end(); it++ )  
             std::cout << (*it);
           v.clear();
        }
     };
    

    In short, I push back some pointers in a vector, later I clear the vector. The question is, does this code has memory leak? I mean by clearing the vector, are the pointers deleted properly?

  • mahmood
    mahmood over 11 years
    can you please give me straghit method (not the smart ptr)??
  • juanchopanza
    juanchopanza over 11 years
    @mahmood It depends on the details of your class, but it is a safe bet that you should do it just before clearing the vector. Iterate over it, deleting each element. Then clear it.
  • Frerich Raabe
    Frerich Raabe over 11 years
    I often wish something like this deleter was readily available; I wonder, could you implement it in terms of std::mem_fun_ptr or std:fun_ptr` or so?
  • scohe001
    scohe001 almost 5 years
    Should this be std::vector< int* >::iterator?
  • juanchopanza
    juanchopanza almost 5 years
    @scohe001 Yes indeed, thanks! I transformed it into C++11 to bypass the issue entirely.