Can anybody explain to me why there is a difference between these two statements?
class A{};
const A& a = A(); // correct
A& b = A(); // wrong
It says
invalid initialization of non-const reference of type A&
from a temporary of type A
Why does const
matter here?
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
References must always be initialized, in the constructor for the class. A class member of reference type must have an initializer provided in all constructors for that class.
In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
Non-const references must be initialised with l-values. If you could initialise them with temporaries, then what would the following do?
int& foo = 5;
foo = 6; // ?!
const
references have the special property that they extend the life of the referee, and since they are const
, there is no possibility that you'll try to modify something that doesn't sit in memory. For example:
const int& foo = 5;
foo = 6; // not allowed, because foo is const.
Remember that references actually have to refer to something, not just temporary variables. For example, the following is valid:
int foo = 5;
int& bar = foo;
bar = 6;
assert(foo == 6);
The terminology on this is a little confusing; you may want to research them a bit further. Here's the short answer though:
You are assigning a temporary object (the result of calling the class's constructor) to a variable. A temporary object is an R-value. You can't assign an R-value to a non-const reference.
You are allowed to assign an R-value to a const reference, although the rationale for allowing it is pretty obscure.
In C++ language it is illegal to attach a non-const reference to an rvalue, while it is perfectly OK to attach a const reference to an rvalue. For example, this is legal
const int& r = 5;
while this is not
int &r = 5; // ERROR
A temporary object of type A
returned by the expression A()
is an rvalue, so the above rule applies in your case as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With