C++11 rvalue reference vs const reference

后端 未结 5 1200
你的背包
你的背包 2020-12-06 02:54

This may be obvious but I think it is something difficult to me. Given this:

void test(std::string&&) { }

std::string x{\"test\"};
test(std::move(x)         


        
5条回答
  •  暖寄归人
    2020-12-06 03:39

    When you call std::move(x), an rvalue reference to the underlying data, test, will be returned. You are allowed to pass rvalue references as const (and const only!) reference parameters because an rvalue reference is implicitly convertible to a const reference. They are arguably the same thing from the function's point of view (a read only parameter). If you removed the const-qualifier of your parameter, this code would not compile:

    void other_test(std::string&) { }
    std::string x{"test"};
    other_test(std::move(x)); //not okay because
    //the function can potentially modify the parameter.
    

    See Bo Qian's youtube video on rvalue vs lvalue.

提交回复
热议问题