Reputation: 1435
I was wondering what would happen to an iterator pointing to the end of a vector after I emplace_back on it.
Example:
std::vector<int> v;
for(int i = 0; i != 50; ++i)
{
auto it = v.end();
v.emplace_back(i);
if(it != v.end())
cout << i << " ";
}
This code does what I kinda expected but it still feels a bit strange.
I didn't find anything about it on the emplace_back cppreference.
So does anybody know if this is defined behavior or just the compiler that decided to implement it like this?
Upvotes: 0
Views: 382
Reputation: 40842
The code results in undefined behavior:
If the new
size()
is greater thancapacity()
then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
So the past-the-end iterator (end()
) is invalidated in any case.
That you see the seemingly correct result does not mean that your code is correct. Depending on the implementation and if the new size()
is not greater than capacity()
, then the old end iterator might point to the last element, but not because it is guaranteed by the specification, but just because due to how the implementation was done, and even then there is no guarantee that the application remains in a valid state if you use the old end
iterator.
Upvotes: 3