6

Possible Duplicate:
Does a const reference 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?
Community
  • 1
  • 1
AlexDan
  • 3,203
  • 7
  • 30
  • 46

2 Answers2

8

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 1
    :I know that expressions return value, but how this values are stored in f(1), does the compiler simply assign f(1) to 1 like this : int f(1)=1; or something else ? – AlexDan Mar 06 '12 at 14:48
3

Binding a temporary to a const& extends the lifetime of the temporary to the lifetime of the reference.

pmr
  • 58,701
  • 10
  • 113
  • 156
  • if it extends the lifetime of the temporary, then where f(1) is get stored and does it have it's own address and can be changed like normal variable ? – AlexDan Mar 06 '12 at 14:31
  • @AbdessamadBond Whether it can be changed like a normal variable is (I think) an open question; you'd need a `const_cast` to be able to change it, and even then, the results might be undefined behavior. (I think the intent was that they be undefined behavior, but I'm far from sure that wording requiring this actually appears in the standard.) – James Kanze Mar 06 '12 at 14:39
  • @JamesKanze The only case where UB can be caused by a `const_cast` is if the object has been declared `const`. As far as I can see, this is never the case for a temporary. – pmr Mar 06 '12 at 14:53
  • 1
    @pmr That's the usual case (and an rvalue of non-class type isn't cv-qualified). I know that there was intent at one point to extend this rule to temporaries bound to references; I don't know what became of that intent. (The issue comes up if you have a `void f(int const&)`, and you call it with `f(3)`. Is the compiler required to create a new temporary each time? Or can it assume that the temporary `3` hasn't changed?) – James Kanze Mar 06 '12 at 15:14