完美转发(perfect forwarding) 是指函数模板在向其他函数传递参数时该如何保留该参数的左右值属性的问题。

也就是说函数模板在向其他函数传递自身形参时,如果相应实参是左值,它就应该被转发为左值;同样如果相应实参是右值,它就应该被转发为右值

这样做是为了保留在其他函数针对转发而来的参数的左右值属性进行不同处理(比如参数为左值时实施拷贝语义;参数为右值时实施移动语义)的可能性。

如果将自身参数不分左右值一律转发为左值,其他函数就只能将转发而来的参数视为左值,从而失去针对该参数的左右值属性进行不同处理的可能性。

一个完美转发的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

void fun(int &x) { cout << "lvalue ref" << endl; }
void fun(int &&x) { cout << "rvalue ref" << endl; }
void fun(const int &x) { cout << "const lvalue ref" << endl; }
void fun(const int &&x) { cout << "const rvalue ref" << endl; }

template<typename T>
void PerfectForward(T &&t) { fun(std::forward<T>(t)); }

int _tmain(int argc, _TCHAR* argv[])
{
PerfectForward(10); // rvalue ref

int a;
PerfectForward(a); // lvalue ref
PerfectForward(std::move(a)); // rvalue ref

const int b = 8;
PerfectForward(b); // const lvalue ref
PerfectForward(std::move(b)); // const rvalue ref

system("pause");
return 0;
}

可以看到,左右值属性完美地保留了。其核心就在std::forward这个模板函数。


版权声明:本文为CSDN博主「一如当初」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/aqtata/article/details/35372769