The code here is simple:
int main() {
vector<string> v;
v.push_back("hello");
string& x = v[0];
v.push_back("world");
cout << x << endl;
return 0;
}
Why is there a runtime error? Please explain it in detail.
1 Answer 1
Have a read through a reference : std::vector::push_back. Specifically the part that says :
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.
When you pushed back the second string into the vector, it appears it had to re-allocate memory, because there wasn't enough capacity for the second string. This re-allocation moved the entire vector data elsewhere in memory - including the first string you pushed into it. So the reference to that first string became a dangling reference, and de-referencing it has undefined behavior.
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. (emphasis mine)