在派生对象上移动构造函数
当派生对象具有移动构造函数,并且基础对象也具有移动语义时,从派生对象移动构造函数调用基础对象移动构造函数的正确方法是什么?
我首先尝试了最明显的事情:
Derived(Derived&& rval) : Base(rval)
{ }
但是,这似乎最终调用了 Base 对象的复制构造函数。然后我尝试在这里显式使用 std::move
,如下所示:
Derived(Derived&& rval) : Base(std::move(rval))
{ }
这有效,但我很困惑为什么它是必要的。我认为 std::move 仅仅返回一个右值引用。但由于在此示例中 rval
已经是右值引用,因此对 std::move
的调用应该是多余的。但如果我在这里不使用 std::move ,它只会调用复制构造函数。那么为什么需要调用 std::move
呢?
When you have a derived object with a move constructor, and the base object also has move semantics, what is the proper way to call the base object move constructor from the derived object move constructor?
I tried the most obvious thing first:
Derived(Derived&& rval) : Base(rval)
{ }
However, this seems to end up calling the Base object's copy constructor. Then I tried explicitly using std::move
here, like this:
Derived(Derived&& rval) : Base(std::move(rval))
{ }
This worked, but I'm confused why it's necessary. I thought std::move
merely returns an rvalue reference. But since in this example rval
is already an rvalue reference, the call to std::move
should be superfluous. But if I don't use std::move
here, it just calls the copy constructor. So why is the call to std::move
necessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
rval
不是右值。它是移动构造函数体内的左值。这就是为什么我们必须显式调用 std::move 的原因。请参阅此。重要的注意事项是
rval
is not a Rvalue. It is an Lvalue inside the body of the move constructor. That's why we have to explicitly invokestd::move
.Refer this. The important note is
命名的 R 值参考被视为 L 值。
所以我们需要
std::move
将其转换为 R-Value。Named R-value references are treated as L-value.
So we need
std::move
to convert it to R-Value.您确实应该使用 std::forward(obj) 而不是 std::move(obj)。 Forward 将根据 obj 的内容返回正确的右值或左值,而 move 会将左值转换为右值。
You really should use std::forward(obj) rather than std::move(obj). Forward will return the proper rvalue or lvalue based on the what obj is whereas move will turn an lvalue into an rvalue.