【发布时间】:2012-04-30 20:12:55
【问题描述】:
This examplestd::forward 的用法让我很困惑。这是我编辑的版本:
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
struct A{
A(int&& n) { cout << "rvalue overload, n=" << n << "\n"; }
A(int& n) { cout << "lvalue overload, n=" << n << "\n"; }
};
template<typename> void template_type_dumper();
template<class T, class U>
unique_ptr<T> make_unique(U&& u){
//Have a "fingerprint" of what function is being called
static int dummyvar;
cout<<"address of make_unique::dummyvar: "<<&dummyvar<<endl;
//g++ dumps two warnings here, which reveal what exact type is passed as template parameter
template_type_dumper<decltype(u)>;
template_type_dumper<U>;
return unique_ptr<T>(new T(forward<U>(u)));
}
int main()
{
unique_ptr<A> p1 = make_unique<A>(2); // rvalue
int i = 1;
unique_ptr<A> p2 = make_unique<A>(i); // lvalue
}
输出是
address of make_unique::dummyvar: 0x6021a4
rvalue overload, n=2
address of make_unique::dummyvar: 0x6021a8
lvalue overload, n=1
关于引用 template_type_dumper 的警告显示,在第一个实例化中,decltype(u) = int&& 和 U = int,第二个实例化为 decltype(u) = int& 和 U = int&。
很明显,正如预期的那样,有两种不同的实例化,但她是我的问题:
-
std::forward怎么能在这里工作?在第一个实例化中,它的模板参数显式为U = int,它怎么知道它必须返回一个右值引用?如果我改为指定U&&会发生什么? -
make_unique被声明为采用右值引用。为什么u可以是左值引用?有什么我遗漏的特殊规则吗?
【问题讨论】:
-
你错过了reference collapsing。
标签: c++ templates c++11 rvalue-reference perfect-forwarding