- 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
deleteon variables that aren’t declared with the
newkeyword 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.
- No. You explicitly have to call
delete myVec[index]as you iterate over all elements.
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.