概述
完美转发
std::forward 实现完美转发,作用就是保持传参参数属性不变,如果原来的值是左值,经std::forward处理后该值还是左值;如果原来的值是右值,经std::forward处理后它还是右值。
详细说明见代码注释
代码
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
//左值引用
void process(int& x)
{
cout << "process(int&)" << '\t' << x << endl;
cout << endl;
}
//右值引用
void process(int&& x)
{
cout << "process(int&&)" << '\t' << x << endl;
cout << endl;
}
//不完美转发
void Forward1(int&& x)
{
cout << "Forward1(int&& x)" << endl;
process(x); //不是完美转发,x被当做左值,调用process(int& x)
}
//完美转发
void Forward2(int&& x)
{
cout << "Forward2(int&& x)" << endl;
process(forward<int>(x)); //完美转发,x被当做右值
}
int main()
{
int a = 5;
cout << "a左值引用" << endl;
process(a);
cout << "常量1:右值引用" << endl;
process(1);
cout << "move(a)右值引用" << endl;
process(move(a)); //move语句将a视作右值
cout << "move(a) 不完美转发" << endl;
Forward1(move(a));
cout << "move(a) 完美转发" << endl;
Forward2(move(a));
}
测试结果: