clearing a vector of pointers [duplicate]

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.

Leave a Comment