Let's start with this sample code in C ++:
#include <vector> #include <iostream> int main() { std::vector<int> vec; vec.push_back(0); for (int i = 1; i < 5; i++) { const auto &x = vec.back(); std::cout << "Before: " << x << ", "; vec.push_back(i); std::cout << "After: " << x << std::endl; } return 0; }
The code is compiled with g++ test.cc -std=c++11 -O0 , and below is the result:
Before: 0, After: 0 Before: 1, After: 0 Before: 2, After: 2 Before: 3, After: 3
I expected the second line of output would be
Before: 1, After: 1
since x refers to an element in a vector that should not be changed by adding elements to the vector.
However, I have not yet read the parsed code or conducted any other investigations. Also I do not know if this behavior is undefined in the language standard.
I want this to be explained. Thanks.
source share