以下代码使 VC2010 失败:
//code1
std::string& test1(std::string&& x){
return x;
}
std::string str("xxx");
test1(str); //#1 You cannot bind an lvalue to an rvalue reference
//code2
std::string&& test1(std::string&& x){
return x; //#2 You cannot bind an lvalue to an rvalue reference
}
有一些文章解释#1,但我不明白为什么#2 也失败。
让我们看看 std::move 是如何实现的
template<class _Ty> inline
typename tr1::_Remove_reference<_Ty>::_Type&&
move(_Ty&& _Arg)
{ // forward _Arg as movable
return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg);
}
- move 的参数仍然是一个右值引用,但是 move(str) 是可以的!
- 移动也返回右值。
std:move 的魔力是什么?
谢谢
最佳答案
std::move
的参数看起来像是一个右值引用,这看起来确实令人困惑 - 为什么你可以调用 move(str)
, 当 str
不是右值?
这里的技巧是右值引用在模板参数上的工作令人困惑:
如果模板参数T
是int
, 然后 T&&
将是一个右值引用 int&&
.
但是如果 T
是左值引用 int&
, 然后 T&&
也将是左值引用 int&
.
这是因为方式&
和 &&
合并:
Type & && == Type &
Type && & == Type &
Type & & == Type &
Type && && == Type &&
所以当你调用move(str)
, T
是std::string&
, 和 move<std::string&>
的参数类型也是std::string&
- 一个左值引用,它允许函数调用编译。然后都是move
所要做的就是将值转换为右值引用。
关于c++ - std :move 的魔力是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12193143/