Garbage value in reference of vector element after pushing back

I know the title sounds very confusing.

Consider this code:

#include <bits/stdc++.h>
using namespace std;

int main(){
    vector<int> a;
    a.push_back(123);
    int &x = a.back();
    cout << x << ' ';
    a.push_back(0);
    cout << x << ' ';
}

The output I get is:
123 -853600432

Why is the second number not 123?

The previous message isn’t quite correct in the sense that

#include <bits/stdc++.h>
using namespace std;

int main(){
    vector<int> a;
    a.push_back(123);
    int &x = a[0];
    cout << x << ' ';
    a.push_back(0);
    cout << x << ' ';
}

also prints 123 followed by some garbage. See vector::push_back - C++ Reference for the correct answer:

If a reallocation happens, all iterators, pointers and references related to the container are invalidated.

In general, it’s not safe to store references / iterators to vectors unless the vector isn’t changing size.

2 Likes