void another_func(string &&str) {
cout << "右值str1" << endl;
}
void another_func(string& str) {
cout << "左值str2" << endl;
}
template <typename T>
void func(T&& external_arg) {
std::string local_str = "hello";
// 錯誤!local_str 是左值,std::forward 會錯誤地嘗試移動它
another_func(std::forward<T>(local_str));//如果傳入的是右值預期不轉發,但實際也會轉發
another_func(std::forward<T>(external_arg));
//// 正確做法1:如果你想移動 local_str
//another_func(std::move(local_str));
//// 正確做法2:如果你只想傳遞它的值(拷貝)
//another_func(local_str);
}
string str1 = "1";
func(str1);
cout << "------------" << endl;
func(string("2"));
總結,局部變量最好不要使用完美轉發.