看一段代码
#include <iostream>
#include <vector>
class A {
public:
A() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A(const A&) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A(A&&) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
~A() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
void Test(A&& a) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
void Test(A& a) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
template <class T>
void passForward(T&& t) {
// 进来时,t类型为 A&&
std::cout << "不转发" << std::endl;
A a(t); // 由于右值引用为左值,无法匹配移动构造函数
std::cout << "使用forward转发 " << std::endl;
A b(std::forward<T>(t)); // 使用forward转发,格式是: forward<T>
std::cout << "使用static_cast " << std::endl;
A c(static_cast<T&&>(t)); // 这样好像也行
}
int main() {
A a;
passForward(std::move(a)); // 移动语义,让编译器把a视为右值
return 0;
}
测试结果:
个人理解:完美转发的一个作用是,使中间的一层工厂模板函数能正确调用匹配参数的构造函数。