1

In C++, why am I allowed to do:

const int& x = 2;

but not:

int& y = 2;

?

The latter gives me the compiler error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’.

  • 2
    because you can't change constant/rvalue values. It's like you'd attempt to write `2 = 5;` – kambala Jul 09 '14 at 15:29
  • You can bind rvalues to references to `const` because you're promising the compiler that you will not modify the value. If you were able to do `int& x = 2; x = 10;` it wouldn't make much sense, you'd be changing the value of, not only a temporary value, but a number. – David G Jul 09 '14 at 15:35

2 Answers2

1

To understand what is going on here you need to recall the meaning of having a reference variable: it is a variable that refers to some other value, which is stored in some other place in memory.

Now recall the difference between a const and a non-const reference: the latter refers to a modifiable place in memory, while the former refers to a non-modifiable one.

It should be clear now why you cannot initialize a modifiable reference with a literal: the compiler does not have a place in memory that could be modified through your non-const reference. When the reference is const, the compiler can provide such a place for you, in the same way that it does for string literals. Theoretically, it could have done the same thing for non-const references; however, doing so would very likely hide a coding error, so language designers decided against it.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    "Theoretically, it could have done the same thing for non-const references" <-- they did that in C++11 with rval references like `int &&i = 4; i = 8;` – Lasse Reinhold Jul 09 '14 at 20:08
0

Well, to put it simple, the constant "2" you are using doesn't really have its "own" memory region. It is therefore impossible to create a reference that point on this memory region.

These kind of special values also called "r-value" must be handled with r-value references or const references:

int&& x;
const int& x;
Jiwan
  • 731
  • 4
  • 11