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

前端 未结 11 1805
长情又很酷
长情又很酷 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:28

    Why is discussed in the C++ FAQ (boldfacing mine):

    In C++, non-const references can bind to lvalues and const references can bind to lvalues or rvalues, but there is nothing that can bind to a non-const rvalue. That's to protect people from changing the values of temporaries that are destroyed before their new value can be used. For example:

    void incr(int& a) { ++a; }
    int i = 0;
    incr(i);    // i becomes 1
    incr(0);    // error: 0 is not an lvalue
    

    If that incr(0) were allowed either some temporary that nobody ever saw would be incremented or - far worse - the value of 0 would become 1. The latter sounds silly, but there was actually a bug like that in early Fortran compilers that set aside a memory location to hold the value 0.

提交回复
热议问题