c++functionreferencereturntemporary-objects

What happens when I assign a temporary int to a const reference in C++?


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

  1. does making the reference const will give f(1) a long life ?
  2. if yes, where f(1) is gonna be stored ?
  3. and is that mean that x also did not get destroyed when it run out of scope?
  4. what is the difference between f(1) and x?

Solution

  • 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.