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
- does making the reference const will give f(1) a long life ?
- if yes, where
f(1)is gonna be stored ? - and is that mean that
xalso did not get destroyed when it run out of scope? - what is the difference between
f(1)andx?
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 forconstreferences.2) Anywhere the compiler wants, but probably on the stack.
3) Maybe. It depends on whether the compiler copied
xor performed copy elision. Since the type isint, 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 callsint f(int)and evaluates to an rvalue.