How come a non-const reference cannot bind to a temporary object?

前端 未结 11 2104
长情又很酷
长情又很酷 2020-11-21 05:19

Why is it not allowed to get non-const reference to a temporary object, which function getx() returns? Clearly, this is prohibited by C++ Standard but I am in

11条回答
  •  深忆病人
    2020-11-21 05:25

    The main issue is that

    g(getx()); //error
    

    is a logical error: g is modifying the result of getx() but you don't have any chance to examine the modified object. If g didn't need to modify its parameter then it wouldn't have required an lvalue reference, it could have taken the parameter by value or by const reference.

    const X& x = getx(); // OK
    

    is valid because you sometimes need to reuse the result of an expression, and it's pretty clear that you're dealing with a temporary object.

    However it is not possible to make

    X& x = getx(); // error
    

    valid without making g(getx()) valid, which is what the language designers were trying to avoid in the first place.

    g(getx().ref()); //OK
    

    is valid because methods only know about the const-ness of the this, they don't know if they are called on an lvalue or on an rvalue.

    As always in C++, you have a workaround for this rule but you have to signal the compiler that you know what you're doing by being explicit:

    g(const_cast(getX()));
    

提交回复
热议问题