Yes this is true. When you call:
return v;
a temporary copy of v and
const int &myIntRef = f()[0];
initializes your link to the first element of this temporary copy. After this line, a temporary copy no longer exists, which means that myIntRef is an invalid reference, the use of which creates undefined behavior.
What you need to do:
std::vector<int> myVector = f(); const int &myIntRef = myVector[0]; std::cout << myIntRef << std::endl;
which (thanks to elision copying) uses the assignment operator to initialize the myVector object with v without creating a copy of v . In this case, the lifetime of your link is equal to the lifetime of the myVector object, which makes it a perfectly valid code.
And to your second question:
“Also, is there a valid fix, or is it still a bug?”
const int myIntCopy = f()[0];
Yes, this is another possible solution. f()[0] will access the first element of the temporary copy and use its value to initialize the variable myIntCopy . It is guaranteed that the copy v returned by f() exists at least until the whole expression has been executed, see C ++ 03 Standard 12.2 Temporary objects §3:
Temporary objects are destroyed as the last step in evaluating the full expression (1.9), which (lexically) contains the point at which they were created.
Liho
source share