c++ 完美转发

测试代码:

void process(int& x) { 
	std::cout << "处理左值: " << x << "\n";
	x *= 2;
}

void process(int&& x) { 
	std::cout << "处理右值: " << x << "\n";
	x++;
}

template 
void param_wrapper(T&& arg) { // T&& 是万能引用
	process(std::forward(arg));  // 完美转发, 转发 arg
}

template 
void params_wrapper_2(T arg) {
	process(arg);  // 无论传入左值还是右值,arg 均被视为左值。
}

template 
void params_wrapper_3(T&& arg) {
	process(arg);      // 错误!始终调用左值版本
}

// 万能引用&完美转发,核心作用是‌在泛型编程中无损传递参数保留其原始值类别(左值/右值)和类型修饰符(const/volatile)
// ,从而避免不必要的拷贝、提升性能并确保语义正确性。
void testWanMeiZHuanfa() { // 测试万能引用&完美转发。 
	int a = 10;
	param_wrapper(a);       // 传入左值 → 调用 process(int&)
	cout << "a: " << a << endl;
	param_wrapper(20);      // 传入右值 → 调用 process(int&&)
	param_wrapper(std::move(a)); // 传入右值引用 → 调用 process(int&&)
	cout << "a: " << a << endl << endl;

	// 反面教材,修改不了变量值
	int b = 9527;
	params_wrapper_2(b); // 处理左值: 9527
	cout << "b: " << b << endl; // b: 9527

	params_wrapper_2(std::move(b)); // 处理左值: 9527
	cout << "b: " << b << endl << endl; // b: 9527

	// 反面教材,没用完美转发
	int c = 9527;
	// 使用万能引用,但没用完美转发,左值,能修改变量值
	params_wrapper_3(c); // 处理左值: 9527
	cout << "c: " << c << endl; // c: 19054
	// 使用万能引用,但没用完美转发,右值也认为是左值,能修改变量值
	params_wrapper_3(std::move(c)); // 处理左值: 19054
	cout << "c: " << c << endl; // c: 38108
}

打印:

c++ 完美转发_第1张图片

ok, 有时间再深入研究。

你可能感兴趣的:(c/c++,c++,开发语言)