Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why std::move takes forward_reference instead of lvaue reference [duplicate]

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(moveInQuestion(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?

like image 853
RaGa__M Avatar asked Jul 04 '17 09:07

RaGa__M


1 Answers

The usual example is generic code like

template<class T>
T frob() {
    std::vector<T> x = /* ... */;
    return std::move(x[0]);
}

With your move, this breaks when T is bool, since in that case x[0] is a prvalue proxy reference rather than an lvalue.

like image 75
T.C. Avatar answered Sep 30 '22 13:09

T.C.