The vector is deleted, not the objects.
The following means that you save pointers in the vector v
:
std::vector<Object*> v;
You could do this:
std::vector<Object> v;
in which case you get many objects, but then you get copies of your objects which at times is either not possible or not something you want (although newer version of the C++ compiler can do a move instead of a copy, but I don't think that would work in this case...)
Another way if you want the Objects to be allocated and then automatically deleted is to use a smart pointer.
#include <memory>
std::vector<std::shared_ptr<Object> > v;
In that case the Objects are allocated by you and freed whenever the vector gets deleted.
However, your problem is that you initialize objects on the stack and assign that stack pointer to your vector. I would image that your print shows you that the pointer is always the same... meaning that the previous object gets destroyed and a new one created on each iteration.
So I would replace these lines:
std::vector<Object*> v;
Object o (i);
v.push_back(&o);
By something like this:
std::vector<std::shared_ptr<Object> > v;
std::shared<Object> o(new Object(i));
v.push_back(o);
If you do not know anything about shared pointers, I suggest you read up on them. It's very useful whenever you allocate objects with new
. Also there are a few traps with what is called circular references (i.e. check out weak_ptr as well). But in this way you do not have to manage memory and you have good pointers.
If you prefer the solution with the Object by itself, it would be something like this:
std::vector<Object> v;
Object o(i);
v.push_back(o);
This way you avoid the heap, however, you make copies each time you push_back (or a move). So if your objects are big, that's not a good idea.
Also, within your object, if you end up having pointers, using smart pointers will help you greatly too. So that's anyway a good idea to learn about them.