Section 12.2.5 of the standard says:
A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits. In all these cases, the temporaries created during the evaluation of the expression initializing the reference, except the temporary to which the reference is bound, are destroyed at the end of the full-expression in which they are created and in the reverse order of the completion of their construction.
I'm trying to understand the following code:
#include <iostream>
const int& foo(const int& fooRef)
{
return fooRef;
} // #0
int main (void)
{
const int& numberRef = foo(5); // #1
std::cout << numberRef; // #2
return 0;
}
On line #1
a temporary object is created and bound to fooRef
. fooRef
is destroyed on line #0
. I thought the temporary should be destroyed here since lifetime-extension is not transitive.
Questions:
What does until the function exits
mean? Does it mean untill it finished executing
?
Why do I get a 5
output. Does a temporary object still exist on line #2
?
How can I interpret the standard quote to figure out how this example works?
Step-by-step atomic walk-through with references to the standard would be greatly appreciated. Thank you!
P. S. An accepted answer here also told the the code is broken
and I do not get, why I get such output of program.
The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
The reference disappears, the object continues to live.
C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
A temporary object is an unnamed object created by the compiler to store a temporary value.
What does until the function exits mean? Does it mean untill it finished executing?
Yes.
Why do I get a 5 output. Does a temporary object still exist on line #2?
Dereferencing a reference which is not bound to a living object is undefined behavior, so you may get 5
as well as 42
as well as anything else (including a crash). You simply cannot have any expectation on a program that has undefined behavior.
How can I interpret the standard quote to figure out how this example works?
Pretty much like you did already.The temporary gets bound to the function parameter fooRef
, which gets destroyed when returning from the function. Since that temporary is bound to the returned value, that object ceases to exist when the function returns. Later on, you are dereferencing a dangling reference, which gives you UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With