[英]Why use std::forward rather than std::move for data member in rvalue reference constructor's initialization list?
I have read these materials: 我读过这些材料:
What's the difference between std::move and std::forward std :: move和std :: forward之间有什么区别
std::move Vs std::forward std :: move Vs std :: forward
this answer is very close to my question, but one is setImage
, the other is rvalue reference constructor, so I'm afraid something subtle exists. 这个答案非常接近我的问题,但一个是
setImage
,另一个是rvalue引用构造函数,所以我担心一些微妙的存在。
class ClassRoom
{
private:
vector<string> students;
public:
ClassRoom(vector<string>&& theStudents)
:students{std::forward<vector<string>>(theStudents)}
{
}
}
class ClassRoom
{
private:
vector<string> students;
public:
ClassRoom(vector<string>&& theStudents)
:students{std::move(theStudents)}
{
}
}
Someone told me forward
is the right method here because one of the usages of forward
is to pass rvalue reference variable to others and guarantee not use it again. 有人告诉我
forward
是正确的方法,因为forward
一个用法是将rvalue引用变量传递给其他人并保证不再使用它。 but I can't figure out why not to use move
here and is what he said right? 但我无法弄清楚为什么不在这里使用
move
,他说的是对的吗?
In this example, both std::move
and std::forward
do the same thing. 在这个例子中,
std::move
和std::forward
都做同样的事情。
This is different if you change the example to a deduced type, eg 如果您将示例更改为推导类型,则会有所不同,例如
template<typename Arg>
ClassRoom(Arg&& theStudents)
:students{std::forward<Arg>(theStudents)}
{
}
vs VS
template<typename Arg>
ClassRoom(Arg&& theStudents)
:students{std::move(theStudents)}
{
}
Then: 然后:
vector<string> local_students = /* ... */;
ClassRoom cr(local_students)
Arg
deduces to vector<string>&
, which means different things happen Arg
推导出vector<string>&
,这意味着会发生不同的事情
Forward: 向前:
forward<vector<string>&>
passes along the lvalue-reference, so the overload of vector::vector
chosen is the copy constructor, local_students
is unaffected forward<vector<string>&>
传递左值引用,因此所选的vector::vector
的重载是复制构造函数, local_students
不受影响
Move: 移动:
move<vector<string>&>
casts the lvalue-reference to rvalue-reference, so the overload of vector::vector
chosen is the move constructor, local_students
is now in the moved-from state move<vector<string>&>
将左值引用转换为rvalue-reference,因此所选的vector::vector
的重载是移动构造函数, local_students
现在处于移动状态
I would use std::move
here. 我会在这里使用
std::move
。 std::forward
is intended to forward universal references. std::forward
旨在转发通用引用。 There is no universal references in this case. 在这种情况下没有通用的参考。 Although in this example it'll be no difference,
std::move
is more concise and more self documenting. 虽然在这个例子中它没有区别,但
std::move
更简洁,更自我记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.