Back to questionsWhat happens when the program reads
JuniorTheoryVery common
What happens when the program reads *it after push_back?
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
auto it = v.begin();
v.push_back(4);
std::cout << *it << '\n';
}Undefined behavior if push_back reallocated: it is then invalid
- Expecting the old elements to stay put: with no spare capacity,
push_backmoves them to a new memory block, anditstill points into the freed one. - Expecting the vector to update
it: nothing changes an iterator when the elements move, so reading*itafter a reallocation is undefined behavior.
- How would calling
v.reserve(4)before takingitchange the outcome? - Which other
std::vectoroperations can invalidate its iterators?