Basically, is the following guaranteed to work, even when the vector reallocates memory (assuming we have the memory to allocate)?
std::vector<int> v = {1,2,3};
for (int i = 0; i < 1000; ++i)
v.push_back(v.back());
cppreference says std::vector::push_back
:
Appends the given element value to the end of the container.
If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise only the end() iterator is invalidated.
It is not apparent to me when the invalidation of the iterators/references (std::vector::back()
here) occurs, as clearly the new allocation has to happen before the element can actually be inserted. Testing on cpp.sh, it did work fine, but I want to be sure that’s not just a coincidence from the implementation (as the EASTL does not work in this case)