c++完美转发注意事项

image


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"));

总结,局部变量最好不要使用完美转发.

posted @ 2025-11-24 17:21  我不是萧海哇~~~  阅读(10)  评论(0)    收藏  举报