error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

Aquarius_Girl picture Aquarius_Girl · Nov 28, 2011 · Viewed 171.2k times · Source

Wrong form:

int &z = 12;

Correct form:

int y;
int &r = y;

Question

Answer

BruceAdi picture BruceAdi · Nov 28, 2011

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid