Perfect forwarding, which means that a function template can "perfectly" forward its own parameters to other functions that are called internally. The so-called perfection means that not only the value of the parameter can be accurately forwarded, but also the left and right value attributes of the forwarded parameter can be guaranteed unchanged.
Detailed explanation of C++11 perfect forwarding and implementation methods
std::forward perfect forwarding
Perfect Forwarding: The Solution
Universal reference and perfect forwarding test code
#include<iostream>
using namespace std;
//重载被调用函数,查看完美转发的效果
void bar(string & t) {
cout << "bar收到参数:string &" << endl;
}
void bar(const string & t) {
cout << "bar收到参数:const string &" << endl;
}
void bar(string && t) {
cout << "bar收到参数:string &&" << endl;
}
void bar(const string && t) {
cout << "bar收到参数:const string &&" << endl;
}
//万能引用与完美转发函数模板
template <typename T>
void foo(T&& value)
{
bar(forward<T>(value));
}
int main()
{
//传给foo一个string &
string str1;
string & str2 = str1;
foo(str2);
//传给foo一个string
foo(str1);
//传给foo一个const string
const string str3;
foo(str3);
//传给foo一个const string &
const string & str4 = str1;
foo(str4);
//传给foo一个string &&
foo(move(str1));
//传给foo一个const string &&
foo(move(str3));
return 0;
}