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?
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.
In your case vector
holds a copy of f
, not a pointer. On erase
it will just destroy that copy.
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