在派生对象上移动构造函数

发布于 2024-09-30 22:29:29 字数 526 浏览 1 评论 0原文

当派生对象具有移动构造函数,并且基础对象也具有移动语义时,从派生对象移动构造函数调用基础对象移动构造函数的正确方法是什么?

我首先尝试了最明显的事情:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

流年里的时光 2024-10-07 22:29:29

rval 不是右值。它是移动构造函数体内的左值。这就是为什么我们必须显式调用 std::move 的原因。

请参阅。重要的注意事项是

请注意上面的参数 x 是
被视为内部的左值
移动函数,即使它是
声明为右值引用
范围。这就是为什么有必要
说 move(x) 而不是仅仅 x 当
传递到基类。这
是 move 的一个关键安全功能
旨在防止的语义
不小心从某些地方搬了两次
命名变量。所有动作仅发生
来自右值,或使用显式强制转换
右值,例如使用 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 invoke std::move.

Refer this. The important note is

Note above that the argument x is
treated as an lvalue internal to the
move functions, even though it is
declared as an rvalue reference
parameter. That's why it is necessary
to say move(x) instead of just x when
passing down to the base class. This
is a key safety feature of move
semantics designed to prevent
accidently moving twice from some
named variable. All moves occur only
from rvalues, or with an explicit cast
to rvalue such as using std::move. If
you have a name for the variable, it
is an lvalue.

蓝颜夕 2024-10-07 22:29:29

命名的 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.

往事风中埋 2024-10-07 22:29:29

您确实应该使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文