问题描述
当您的派生对象具有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
.
引用此.重要说明是
这篇关于在派生对象上移动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!