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:
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.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.
Is it true that when I am done with the vector I must loop through it and call delete on each pointer?
Well, you don't have to loop by hand, you can also use an algorithm:
#include <vector>
#include <algorithm>
#include <memory>
int main()
{
std::vector<Base*> vec;
vec.push_back(new Derived());
vec.push_back(new Derived());
vec.push_back(new Derived());
// ...
std::for_each(vec.begin(), vec.end(), std::default_delete<Base>());
}
If you don't have a C++0x compiler, you can use boost:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/construct.hpp>
std::for_each(vec.begin(), vec.end(), boost::lambda::delete_ptr());
Or you can write your own functor:
struct delete_ptr
{
template <class T>
void operator()(T* p)
{
delete p;
}
};
std::for_each(vec.begin(), vec.end(), delete_ptr());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With