Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does myVector.erase(myObject) call delete on myObject?

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?

like image 842
JnBrymn Avatar asked Dec 13 '22 20:12

JnBrymn


2 Answers

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.

like image 198
fredoverflow Avatar answered Jan 03 '23 02:01

fredoverflow


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

like image 30
Kirill V. Lyadvinsky Avatar answered Jan 03 '23 02:01

Kirill V. Lyadvinsky