I have a vector that I fill with pointers to objects. I am trying to learn good memory management, and have a few general questions:
- Is it true that when I am done with the vector, I must loop through it and call delete on each pointer?
- Why don't I have to call delete on the vector or any other variable I declare without the new statement, but delete must be called on pointers?
- Does C++ handle freeing the pointers' memory for me if the vector is declared in a function which returns (causing the vector to go out of scope)?
Well, you don't have to loop by hand, you can also use an algorithm:
If you don't have a C++0x compiler, you can use boost:
Or you can write your own functor:
delete
on variables that aren't declared with thenew
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.delete myVec[index]
as you iterate over all elements.Ex:
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.Everything you allocate with
new
you have todelete
later on. Objects that you don't explicitly allocate withnew
shouldn't youdelete
.If you don't want to manage the objects manually but want the vector to "own" them, it might be better to store the objects by value instead of storing pointers to them. So instead of
std::vector<SomeClass*>
you could usestd::vector<SomeClass>
.As an alternative to
boost::ptr_vector
as mentioned by David Titarenco, you can easily modify std::vector to automatically free memory for containing pointers on deletion:All functionality provided by std::vector is inherited so you would add items the same way:
You can also use std::unique_ptr if you have access to C++0x. It replaces the deprecated std::auto_ptr that couldn't be used in containers.