【发布时间】:2013-06-30 00:37:09
【问题描述】:
尝试了解使用 std::forward 和 auto&& 变量是否是传递这些变量以允许移动的正确方法。
假设有一个函数:
void moveWidget(Widget&& w);
和调用者——两个变量分别引用右值和左值:
Widget w;
auto&& uniRefLV = w; // lvalue initialiser,
// uniRefLV's type is Widget&
auto&& uniRefRV = std::move(w); // rvalue initialiser,
// uniRefRV's type is Widget&&
我们知道auto&& 类型的变量是一个通用引用,因为发生了类型推导。这意味着uniRefRV 和uniRefLV 都是通用参考。
在我的示例中,uniRefRV 显然是 rvalue 和 uniRefLV 是 lvalue 但从概念上讲它们都是 通用引用 和如果定义不同,它们可以表示 rvalue 或 lvalue。
现在,我想致电moveWidget() 并完善这些通用引用类型。该指南(由 Scott Meyers 撰写)说:
通过
std::move传递和返回右值引用,通过std::forward通用引用。
除非我完全误解了该指南,否则使用std::forward 似乎是合乎逻辑的。但让我们考虑所有可能的选择:
// (1) std::move:
moveWidget(std::move(uniRefLV)); // Compiles and looks fine
// but violates the guideline?
// (unconditionally casts lvalue to rvalue)
moveWidget(std::move(uniRefRV)); // Same as above - but not an issue here
// as we cast rvalue to rvalue
// (2) std::forward with Widget:
moveWidget(std::forward<Widget>(uniRefLV)); // Compiles, follows the guideline
// but doesn't look right - what if
// we didn't know Widget's type?
moveWidget(std::forward<Widget>(uniRefRV)); // Same as above
// (3) std::forward with decltype:
moveWidget(std::forward<decltype(uniRefLV)>(uniRefLV)); // Fails to compile! (VC10)
// follows the guideline
// has nice and short syntax :)
moveWidget(std::forward<decltype(uniRefRV)>(uniRefRV)); // Compiles fine
您认为我们应该平等对待uniRefLV 和uniRefRV 这两个引用吗?我们应该使用三个选项中的哪一个来实现完美转发?
【问题讨论】:
-
其实
std::forward<int>(uniRef)等价于std::move(uniRef)。 -
使用
std::forward<decltype(uniRef)>(uniRef)。这避免了明确地说int。 -
@MWid
std::move也避免了这种情况。而且它还避免说两次uniRef。 -
@R.MartinhoFernandes 当然,但是如果我们不知道
uniRef是右值还是左值引用并且我们只想从右值引用中窃取,那么使用std::forward<decltype(uniRef)>(uniRef)是合理的. -
感谢您提出 decltype(uniRef) - 我将此添加到我的问题的修订版中,因为它有助于更好地解释我们有哪些选择。