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?
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);