views:

68

answers:

5

Similar to this question but with objects instead of pointers.

If I have the following code

Foo f;
vector<Foo> vect;
vect.push_back(f);
vect.erase(vect.begin());

Where does my object go? Is delete called on it? What if someone else holds a pointer to it? Is this a memory leak?

+2  A: 

In your case vector holds a copy of f, not a pointer. On erase it will just destroy that copy.

Kirill V. Lyadvinsky
+7  A: 

push_back stores a copy of f in the vector, and erase destroys it. f itself is not affected by that.

All pointers, references and iterators to an element in a vector are invalidated when you erase it. Using them to access the element after erase yields undefined behavior.

FredOverflow
A: 

Yes, erase calls the destructor for the object(s) in the vector.

When the object is inserted into the vector, it's copy constructor is called and a copy of it is placed into the vector, so if you have a pointer pointing at f (and no the copy of f created for the vector), you don't need to worry about the consequences of deleting objects from the vector.

tsiki
A: 

When pushing back an element, a copy is made. After erasing, the copy is destroyed, but f is still valid. If you have a pointer on the element copied, it will become a dangling reference, meaning that the content pointed by your pointer is invalid. If you are using an iterator on the copied element, it will also become invalid

Scharron
+1  A: 

From cplusplus.com

iterator erase ( iterator position );

iterator erase ( iterator first, iterator last );

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

This invalidates all iterator and references to elements after position or first.

In this case, you still have your object f, because you declared it before copying it (via pushback) into the vector.

When you erase from the vector the destructor is called on the copied object and the vector's iterator are broken.

James