move semantics std::move

纵饮孤独 提交于 2020-01-01 08:24:07

问题


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 ?


回答1:


Think about what happens if T is an lvalue reference, for example MyClass &. In that case, T && would become MyClass & &&, and due to reference collapsing rules, this would be transformed into MyClass & again. To achieve the right result, typename remove_reference<MyClass&>::type&& first removes any reference decorations from the type, so MyClass & is mapped to MyClass, and then the rvalue reference is applied to it, yielding MyClass &&.




回答2:


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:

template < typename T > T&& func(T&& x) { return x; }

int main()
{
        int x;

        int &y = func(x);
}

Further reading: http://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html



来源:https://stackoverflow.com/questions/5529382/move-semantics-stdmove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!