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 ?
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 ?
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 &&
.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