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?
constreferences have the special property that they extend the life of the referee, and since they areconst, there is no possibility that you’ll try to modify something that doesn’t sit in memory. For example:Remember that references actually have to refer to something, not just temporary variables. For example, the following is valid: