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’.
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’.
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.
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;