简体   繁体   中英

move semantics std::move how use it

#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 &&'

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.

This is straight out of the C++0x draft standard (§20.2.3/6):

template <class T> typename remove_reference<T>::type&& move(T&& t) noexcept;

Returns : static_cast<typename remove_reference<T>::type&&>(t) .

Consequently, if you change your move implementation to the following, it works just fine:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM