I searched StackOverflow but couldn't find the answer to this question.
Suppose I have a std::vector<Day *> vector_day
- that is - a vector of pointers to Day
object. Now I push_back
to vector_day
many elements:
vector_day.push_back(new Day(12));
vector_day.push_back(new Day(99));
vector_day.push_back(new Day(71));
...
Now at some point I no longer need vector_day
. What is the right way to free the memory?
It this the correct way:
for (std::vector<Day *>::iterator i = vector_day.begin(); i != vector_day.end(); ++i) {
delete *i;
}
Doesn't this invalidate the vector on each deletion? I am very confused.
The best way is not to put pointers into the vector in the first place if you don't absolutely need to.
But if you do really need to have a vector of pointers, then the way you are doing it is just fine (but .clear()
the vector afterwords, if it won't be immediately destroyed, so that it's not full of dangling pointers)
The statement
delete *it;
has no effect on the iterator. It does not change the iterator, invalidate the iterator, or remove the pointer referred to by the iterator from the collection. All it does is free the memory that the pointer referred to by the iterator points at. The pointer itself must be removed from the collection separately.