【发布时间】:2023-03-29 17:59:02
【问题描述】:
以下代码使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)是可以的!
- move 也返回右值。
std:move 有什么魔力?
谢谢
【问题讨论】:
-
在第二种情况下,
x是一个右值引用,它本身不是一个右值(因为它有一个名字)。
标签: c++ c++11 rvalue-reference