int &z = 12;
On the right side, a temporary object of type int is created from the integral literal 12 , but the temporary cannot be tied to a non-constant reference. Hence the error. This is the same as:
int &z = int(12);
Why is a temporary creation created? Since the link must reference the object in memory and for the object to exist, it must be created first. Because the object is not specified, this is a temporary object. He has no name. From this explanation it became clear why the second case is in order.
A temporary object can be bound to a constant reference, which means you can do this:
const int &z = 12;
C ++ 11 and Rvalue Reference:
For completeness, I would like to add that C ++ 11 introduced rvalue-reference, which can bind to a temporary object. So in C ++ 11 you can write this:
int && z = 12;
Note that there is && intead & . Also note that const no longer required even if the object to which z is attached is a temporary object created from integral literal 12 .
Since C ++ 11 introduced rvalue-reference, int& now called lvalue-reference.
Nawaz Nov 28 2018-11-11T00: 00Z
source share