move semantics std::move how use it

前端 未结 2 814
广开言路
广开言路 2021-01-20 18:10
#include 

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

void main()
{
           


        
相关标签:
2条回答
  • 2021-01-20 18:52

    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);
    }
    
    0 讨论(0)
  • 2021-01-20 18:55

    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.

    0 讨论(0)
提交回复
热议问题