clearing a vector of pointers [duplicate]

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:

Nope you only clear the vector storage. Allocated memory with 'new' is still there.

for (int i =0; i< v.size();i++)
   {
     delete (v[i]);
   } 
   v.clear();

Solution 4:

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 ();