Possible Duplicate:
Does a const reference class member prolong the life of a temporary?
let say that I have a function f
:
int f(int x){return x;}
const int &a=f(1);
I know that f(1)
is just a temporary and i will be destroyed after this statement, but
f(1)
is gonna be stored ?x
also did not get destroyed when it run out of scope?f(1)
and x
?You're confusing expressions with values.
1) The lifetime of the temporary value returned by the expression f(1)
will have its lifetime extended. This rule is unique for const
references.
2) Anywhere the compiler wants, but probably on the stack.
3) Maybe. It depends on whether the compiler copied x
or performed copy elision. Since the type is int
, it doesn't matter.
4) Lots of differences. One is the name of a local variable inside int f(int)
. It is an lvalue. The other is an expression which calls int f(int)
and evaluates to an rvalue.