为什么 std::move 使用 std::remove_reference 实现?
我不太明白 std::move
函数
template <class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
为什么要 remove_reference
? 有人能给我一个简单的解释吗?
I don't understand very well the std::move
function
template <class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
why remove_reference
?
could someone give me a simple explanation ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑一下如果
T
是左值引用(例如MyClass &
)会发生什么。在这种情况下,T &&
将变为MyClass & &&
,并且由于引用折叠规则,这将再次转换为MyClass &
。为了获得正确的结果,typename remove_reference::type&&
首先从类型中删除所有引用装饰,因此MyClass &
映射到 < code>MyClass,然后将右值引用应用于它,产生MyClass &&
。Think about what happens if
T
is an lvalue reference, for exampleMyClass &
. In that case,T &&
would becomeMyClass & &&
, and due to reference collapsing rules, this would be transformed intoMyClass &
again. To achieve the right result,typename remove_reference<MyClass&>::type&&
first removes any reference decorations from the type, soMyClass &
is mapped toMyClass
, and then the rvalue reference is applied to it, yieldingMyClass &&
.因为右值引用对左值引用会衰减为左值引用,并且返回左值引用将具有与您期望从
move
获得的语义不同的语义。编辑:
呵呵,为什么投反对票?查看此代码:
进一步阅读:http://www.justsoftwaresolutions.co.uk/cplusplus /rvalue_references_and_perfect_forwarding.html
Because rvalue reference to lvalue reference would decay to lvalue reference, and returing lvalue reference would have different semantics from those you would expect from
move
.Edit:
Huh, why the downvote? Check out this code:
Further reading: http://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html