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

前端 未结 5 1562
盖世英雄少女心
盖世英雄少女心 2020-11-28 18:42

Wrong form:

int &z = 12;

Correct form:

int y;
int &r = y;

Question:

5条回答
  •  Happy的楠姐
    2020-11-28 19:27

    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
    

提交回复
热议问题