Deleting Vector of Pointers

Hi everyone
I made a vector of pointers and the problem is that I have trouble deleting the pointers in the vector. I used to simply do vector.clear() or vector.erase() however it does not clear the actual memory. And I tried something like this:
1
2
3
4
std::vector<Foo*> Vector;
std::vector<Foo*>::iterator i;
for (i = Vector.begin(); i < Vector.end(); i++)
     delete *i;

Thanks in advance for any help.
If Foo is not polymorphic, don't use pointers at all - just use std::vector<Foo>

If Foo is polymorphic, use a std::vector<std::unique_ptr<Foo>>

Avoid use of raw pointers. http://www.LB-Stuff.com/pointers
Last edited on
Adding on to what @LB said, if you ever find yourself copying the vector you should use std::shared_ptr instead. In general, it behaves just like a normal pointer, but if you want more detail look up std::shared_ptr and std::unique_ptr on the reference here.
@NT3 I would hope that when you copy a vector you don't expect that changing the elements in one changes the elements in the other too. That's not quite what a copy is.
Choosing between deep copy vs shallow copy is a design decision.
The advice on std::shared_ptr and std::unique_ptr are really useful. Thanks everyone for the info.
I find it funny that this website runs on java. :)
Topic archived. No new replies allowed.