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?
Well, you don't have to loop by hand, you can also use an algorithm:
#include
#include
#include
int main()
{
std::vector 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 ());
}
If you don't have a C++0x compiler, you can use boost:
#include
#include
std::for_each(vec.begin(), vec.end(), boost::lambda::delete_ptr());
Or you can write your own functor:
struct delete_ptr
{
template
void operator()(T* p)
{
delete p;
}
};
std::for_each(vec.begin(), vec.end(), delete_ptr());