Take this simplified example:
std::vector< int > v; v.push_back( 1 ); v.insert( v.end()-1, v[ v.size()-1 ] );
output:
-17891602 1
The author of the code, designed to insert a duplicate of the last element before the end of the vector. There are some good ways to do this, but the author decided to use this one.
It worked as "expected" before C ++ 11. This is due to the fact that in the microsoft implementation of the insert in the vector they make a copy of the value for the insert if the inserted value is in the range of the vector.
Now with C ++ 11 there is a version of the insert that uses the r-value reference, which does not need this trick, because it is temporary.
But it is surprising that, using the above code, the compiler decides to take the version of the r-value ref value instead of the version for the link, which inserts an uninitialized value before the end of the vector. Note that the [] operator is returned by reference.
Why did the compiler decide to take the version using the r-value link?
source share