Rvalue Reference is Treated as an Lvalue?

后端 未结 4 1358
小蘑菇
小蘑菇 2020-11-22 09:20

I posted this answer: https://stackoverflow.com/a/28459180/2642059 Which contains the following code:

void foo(string&& bar){
    string* temp = &         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 10:03

    Is bar an rvalue or an lvalue?

    It's an lvalue, as is any expression that names a variable.

    If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

    You can only initialise an rvalue reference with an rvalue expression. So you can pass a temporary string to your function, but you can't pass a string variable without explicitly moving from it. This means your function can assume the argument is no longer wanted, and can move from it.

    std::string variable;
    foo(variable);            // ERROR, can't pass an lvalue
    foo(std::move(variable)); // OK, can explicitly move
    foo("Hello");             // OK, can move from a temporary
    

提交回复
热议问题