mardi 4 juillet 2017

why std::move takes forward_reference instead of lvaue reference

Just to confirm what I understood about std::move

std::move - converts T& to T&& so that the T's move constructor would kick in(if it exist otherwise the copy ctor will play its role unless we aren't externally deleted move ctor/assignment).

when I've looked at the possible implementation of std::move it's like

template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}

The reason it uses remove_reference<T> is because of the reference collapsing that applied over the forward_reference T&&

I just wonder why we need forward reference,couldn't we done that by

template<typename T>
T&& moveInQuestion(T& p){
  return static_cast<T&&>(p);
}

struct someType{};
someType lvalref;
static_assert(is_same<decltype(mymove(lvalref)),decltype(std::move(lvalref))>::value,"");

static_assert hasn't failed.

And I also believe that the value category that meant for std::move is an lvalue with this being the case could moveInQuestion possibly be better than std::move?

Aucun commentaire:

Enregistrer un commentaire