【发布时间】:2017-02-22 11:29:57
【问题描述】:
我目前正试图弄清楚完美转发的工作原理。我已经编写了一段示例代码,据我所知,它可以完美地转发:
void whatIsIt(std::vector<int>&& variable)
{
std::cout << "rvalue" << std::endl;
}
void whatIsIt(std::vector<int>& variable)
{
std::cout << "lvalue" << std::endl;
}
template <class T>
void performPerfectForwarding(T&& variable)
{
whatIsIt(std::forward<T>(variable));
}
int main(int argc, char** argv)
{
std::vector<int> lvalue;
performPerfectForwarding(lvalue);
performPerfectForwarding(std::move(lvalue));
return 0;
}
使用左值调用函数performPerfectForwarding 使其调用whatIsIt 的相应重载,同样适用于使用右值调用它。因此,此代码生成的输出为:
lvalue
rvalue
但是,我问自己以下版本的函数 performPerfectForwarding 会做什么:
1.
template <class T>
void performPerfectForwarding(T& variable)
{
whatIsIt(std::forward<T>(variable));
}
2.
template <class T>
void performPerfectForwarding(T variable)
{
whatIsIt(std::forward<T>(variable));
}
他们都输出:
rvalue
rvalue
现在,我的问题是:这两个替代版本会做什么?它们在任何可能的情况下都有意义吗?与在上述“正确”版本中的应用相比,参考折叠规则在这些情况下如何应用?
【问题讨论】:
标签: c++ c++11 rvalue-reference perfect-forwarding