我有一个可能通过其成员移动通用参数的函数。以下选项哪个更正确:
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] 此声明是不正确的,如@Angew指出,它只是看起来像被移动了两次。与std::move
类似,std::forward
实际上并不会移动任何东西。最多只会移动成员(由后续操作decltype(myhead)::operator=
完成,但这正是目标所在。)
t.head_
是一个左值(因为t
是一个左值)。你需要在decltype内部使用std::forward
。然而,我已经再次检查了标准,并发现整个过程都是不必要的。 - Angew is no longer proud of SO