int &z = 12;
On the right hand side, a temporary object of type int
is created from the integral literal 12
, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:
int &z = int(12); //still same error
Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.
A temporary object can be bound to const reference, which means, you can do this:
const int &z = 12; //ok
For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:
int && z = 12; //C+11 only
Note that there is &&
intead of &
. Also note that const
is not needed anymore, even though the object which z
binds to is a temporary object created out of integral-literal 12
.
Since C++11 has introduced rvalue-reference, int&
is now henceforth called lvalue-reference.