4

I understand why int& x=1 is illegal(you can't have reference to constant value), but I don't understand why const int& x=1 is legal? How can you have reference to the number "1"? It is not even a defined variable.

EDIT: I read the answer given in this post: What happens when I assign a temporary int to a const reference in C++? but can someone explain what does he means "The lifetime of the temporary value returned by the expression f(1) will have its lifetime extended. This rule is unique for const references."? so literals are stored as int on the stack or not? Thanks!

Community
  • 1
  • 1

5 Answers5

3

(you can't have reference to constant value)

You almost got it.

You cannot have a non-constant reference to a constant value.

You can have a constant reference to a constant value. (Which extends the lifetime of said value to the lifetime of that reference).

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
1

The second case with const reference is allowed, because then a temporary object of type int is created, and the reference refers to this temporary object.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

This is a C++ language feature. Click here for an easy explanation.

EDIT

From the link:

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error

Nasser Al-Shawwa
  • 3,573
  • 17
  • 27
0

In this case you have the constant reference to a constant value, which under the hood means creating a temp variable whole life time is bound to the life time of the reference.

Ashalynd
  • 12,363
  • 2
  • 34
  • 37
-1

Because C++ says so. The language is defined this way. The language creators decided to allow it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055