我有一个函数可能会 move 一个通用参数,但通过它们的成员。以下哪个选项更正确:
template<class T>
void fun(T&& t){
myhead_ = std::forward<T>(t).head_;
myrest_ = std::forward<T>(t).rest_;
}
template<class T> void fun(T&& t){
myhead_ = std::forward<decltype(t.head_)>(t.head_);
myrest_ = std::forward<decltype(t.rest_)>(t.rest_);
}
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 指出的那样,此语句是不正确的,它看起来只是 move 了两次。
std::forward
(如 std::move
)实际上并没有 move 任何东西。最多 move 成员(通过后续操作 decltype(myhead)::operator=
但这正是目标。)
最佳答案
您的第一个代码非常好:
template<class T>
void fun(T&& t){
myhead_ = std::forward<T>(t).head_;
myrest_ = std::forward<T>(t).rest_;
}
那是因为标准保证在做
a.b
时和 a
是一个 xvalue(例如一个转发的右值引用),a.b
的结果也是一个外值(即可以从中 move )。另请注意 std::forward
和 std::move
不要自己做任何实际的 move ,它们只是类型转换。所以从 t
搬家没有风险。在您的代码中两次。
关于c++11 - 转发转发引用的单个成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50149972/