在派生对象上移动构造函数 [英] Move constructor on derived object

查看:74
本文介绍了在派生对象上移动构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您的派生对象具有move构造函数,并且基础对象也具有move语义时,从派生对象move构造函数调用基础对象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)
 { }

但是,这似乎最终调用了Base对象的 copy构造函数.然后我在这里明确尝试使用std::move,如下所示:

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))
 { }

这有效,但是我很困惑为什么有必要.我以为std::move仅返回右值引用.但是由于在此示例中rval已经是右值引用,因此对std::move的调用应该是多余的.但是,如果我在这里不使用std::move,它只会调用复制构造函数.那么为什么要调用std::move呢?

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?

推荐答案

rval不是Rvalue.它是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.

引用.重要说明是

请注意,参数x为 视为内部的左值 移动功能,即使它是 声明为右值引用 范围.这就是为什么有必要 说出move(x)而不是x 传到基层.这 是移动的关键安全功能 旨在防止的语义 从某些地方意外移动了两次 命名变量.所有动作仅发生 从右值或显式强制转换 右值,例如使用std :: move.如果 您有一个变量名称,它 是左值.

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.

这篇关于在派生对象上移动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆