Reputation: 2566
What is supposed to happen in the following case:
int functionA() {
return 25;
}
void functionB(const int& ref) {
cout << ref << endl;
}
void start() {
functionB(functionA());
}
When compiling this example, it outputs the correct value 25. How does this work? Should'nt the referenced return value on the stack be deleted (removed from the stack) when using only a reference to it, or is the behaviour undefined?
Upvotes: 10
Views: 4733
Reputation: 476990
There is no "return value on the stack" (let alone a "stack"): functionA
returns an int
by value, so the expression functionA()
is simply a temporary value of type int
. This value binds to the constant reference in functionB
, and since its lifetime is that of the full expression, everything is fine.
Upvotes: 9
Reputation: 129344
This "works" because of const int& ref
- when a reference is const
(guarantees that you don't want to change it), the compiler will produce a temporary object in the calling code (start
in your case), and then pass the reference to that.
If you remove const
it will fail to compile because functionA
's result can't be turned into a reference.
Upvotes: 10