Move Semantics with std::move – How to Use

c++c++11move-semanticsrvalue-referencevisual-c++

#include <type_traits>

template<class T>
typename std::remove_reference<T>::type&& move(T&& v)
{
    return v;
}

void main()
{
    int a;
    move(a);
}

Why doesn't this code compile?

error C2440: 'return' : impossible to convert 'int' in 'int &&'

Best Answer

v is an lvalue in the return statement (named rvalue references are lvalues, for safety reasons), but the return type of move is an rvalue reference (T is int&, but you remove the reference, so you form the type int && in the return type).

You need to static_cast the v to remove_reference<T>::type && first to create an unnamed rvalue reference, when you want to return it.

I'm not sure what your goal is. Either you want to use std::move (like you say in your title), or you want to learn how it would be implemented (like the code you show indicates). It doesn't make sense to try to learn how std::move works without knowing the basic C++ rules. I recommend you to have a look in our C++ Books List. After you have a good grasp about C++, you can learn how std::move works.