What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?

  1. Yes
  2. Vectors are implemented using template memory allocators that take care of the memory management for you, so they are somewhat special. But as a general rule of thumb, you don’t have to call delete on variables that aren’t declared with the new keyword because of the difference between stack and heap allocation. If stuff is allocated on the heap, it must be deleted (freed) to prevent memory leaks.
  3. No. You explicitly have to call delete myVec[index] as you iterate over all elements.

Ex:

for(int i = 0; i < myVec.size(); ++i)
   delete myVec[i];

With that said, if you’re planning on storing pointers in a vector, I strongly suggest using boost::ptr_vector which automatically takes care of the deletion.

Leave a Comment