开发者

move semantics std::move how use it

开发者 https://www.devze.com 2023-02-22 05:48 出处:网络
#include <type_traits> template<class开发者_StackOverflow中文版 T> typename std::remove_reference<T>::type&& move(T&& v)
#include <type_traits>

template<class开发者_StackOverflow中文版 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消