Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 328
AlexDan Avatar asked Mar 06 '12 14:03

AlexDan


2 Answers

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.

like image 197
Ben Voigt Avatar answered Oct 10 '22 19:10

Ben Voigt


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

like image 43
pmr Avatar answered Oct 10 '22 21:10

pmr