Why can you indirectly bind an rvalue to an lvalue reference but not directly?

后端 未结 3 1858
天涯浪人
天涯浪人 2021-02-06 00:06

From what I\'ve read and seen you cannot bind an expression that is an rvalue to an lvalue reference. What I have seen however is that you can bind an rvalue to an rvalue refere

3条回答
  •  佛祖请我去吃肉
    2021-02-06 00:40

    What is the reason behind disallowing binding an rvalue to an lvalue reference?

    No answer to this question can be complete without a reference to the invaluable and distinguished source, The Design and Evolution of C++ by Bjarne Stroustrup.

    In section 3.7 Bjarne writes:

    I made one serious mistake, though, by allowing a non-const reference to be initialized by a non-lvalue. For example:

    void incr(int& rr) { rr++; }
    
    void g()
    {
        double ss = 1;
        incr(ss);    // note: double passed, int expected
                     // (fixed: error in Release 2.0)
    }
    

    Because of the difference in type the int& cannot refer to the double passed so a temporary was generated to hold an int initialized by ss's value. Thus incr() modified the temporary, and the result wasn't reflected back to the calling function.

    I highly recommend The Design and Evolution of C++ for understanding many of the "why questions" one might have, especially regarding the rules that were laid down prior to the C++98 standard. It is an informative and fascinating history of the language.

提交回复
热议问题