c++完美转发注意事项

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"));
总结,局部变量最好不要使用完美转发.

浙公网安备 33010602011771号