I have a function that potentially moves a generic argument but through their members. What of these options is more correct:
This seems the more natural but it is strange because the argument is potentially moved twice [a], which is odd because the object can become invalid.
template<class T> void fun(T&& t){ myhead_ = std::forward<T>(t).head_; myrest_ = std::forward<T>(t).rest_; }
This can't be incorrect but it may not be moving anything.
template<class T> void fun(T&& t){ myhead_ = std::forward<decltype(t.head_)>(t.head_); myrest_ = std::forward<decltype(t.rest_)>(t.rest_); }
This seems correct but too much code.
template<class T> void fun(T& t){ myhead_ = t.head_; myrest_ = t.rest_; } template<class T> void fun(T&& t){ myhead_ = std::move(t.head_); myrest_ = std::move(t.rest_); }
[a] This statement is incorrect as @Angew pointed out, it only looks as if it is moved twice. std::forward
(like std::move
) doesn't actually move anything. At most the member is moved (by the subsequent operation decltype(myhead)::operator=
but that is precisely the objective.)
t.head_
is an lvalue (sincet
is an lvalue). You would have neededstd::forward
inside the decltype. However, I've since double-checked the standard and found that the whole thing is unnecessary. – Multiphase