C++11 rvalue reference vs const reference

后端 未结 5 1202
你的背包
你的背包 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:29

    If you want a function to expressly allow const-Lvalue objects, but expressly disallow Rvalue objects, write the function signature like this:

    void test(const std::string&) { }
    void test(std::string&&) = delete;//Will now be considered when matching signatures
    
    int main() {
        std::string string = "test";
        test(string);//OK
        //test(std::move(string));//Compile Error!
        //test("Test2");//Compile Error!
    }
    

提交回复
热议问题