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

Possible duplicate:
Does the const link refer to temporary life?

let's say i have a function f :

 int f(int x){return x;} const int &a=f(1); 

I know that f(1) is only temporary, and I will be destroyed after this statement, but

  • Does the link const, giving f (1) a long life?
  • if so, where f(1) will be stored?
  • and does this mean that x also cannot be destroyed when leaving the scope?
  • What is the difference between f(1) and x ?
+6
source share
2 answers

You mix expressions with values.

1) The lifetime of the temporary value returned by the expression f(1) will be extended for life. This rule is unique to const links.

2) Anywhere, the compiler wants, but probably on the stack.

3) Maybe. It depends on whether the compiler copied x or performed a copy operation. Since the type is int , it does not matter.

4) A lot of differences. One of them is the name of a local variable inside int f(int) . This is an lvalue. Another is an expression that calls int f(int) and evaluates the value of r.

+8
source

Associating a temporary with const& extends the lifetime of a temporary link resource.

+3
source

Source: https://habr.com/ru/post/910085/


All Articles