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

后端 未结 3 1737
天涯浪人
天涯浪人 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:33

    It's a fundamental rule of C++ and it prevents bugs:

    int foo();
    
    int& x = 3;      // whoops
    int& y = foo();  // whoops (sometimes)
    

    "Rvalue references" (a set of types; not to be confused with actual rvalues) were created at least in part so that you can still do this if you really want to:

    int&& x = 3;     // oh, go on then *sigh*
    int&& y = foo(); // you'd better be sure!
    

    In the previous examples, I bind (or attempt to bind) objects "referenced" by an rvalue expression to a reference.

    Now, I shall bind the object named by an lvalue expression to a reference:

    int i = foo();
    
    int& x = i;      // no problem michael
    

    And to make sure that you really meant to obtain an rvalue reference from an lvalue expression, introducing the incredibly poorly-named std::move:

    int&& x = std::move(i);  // doesn't move anything
    

    These later rules came much, much later than the original, fundamental rule that has doubtless prevented many bugs over the past twenty years.

    Note that Visual Studio has historically accepted T& x = bar() where T is a user-defined type; go figure.

提交回复
热议问题