c++ - 在派生对象上 move 构造函数

标签 c++ c++11 move-semantics

如果派生对象具有 move 构造函数,并且基对象也具有 move 语义,那么从派生对象 move 构造函数调用基对象 move 构造函数的正确方法是什么?

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

 Derived(Derived&& rval) : Base(rval)
 { }

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

 Derived(Derived&& rval) : Base(std::move(rval))
 { }

这行得通,但我很困惑为什么它是必要的。我认为 std::move 只是返回一个右值引用。但是由于在这个例子中 rval 已经是一个右值引用,所以对 std::move 的调用应该是多余的。但是如果我在这里不使用 std::move ,它只会调用复制构造函数。那么为什么需要调用 std::move 呢?

最佳答案

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

请参阅 this .重要的提示是

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.

关于c++ - 在派生对象上 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4086800/

相关文章:

c++ - 为什么 std::move 之后的析构函数调用是必要的?

c++ - 将相似的变量存储在数组中有什么好处吗?

c++ - 右值引用 : Why aren't rvalues implicitly moved?

C++ 返回值优化

c++ - MSB 到 LSB 交换后保留符号和小数

c++ - 为什么代码没有cout?

c++ - 为什么std::map的move构造函数不是noexcept?

c++ - 我在这里使用 std::forward 还是 std::move?

c++ - C++如何处理&&? (短路评估)

c++ - 如何将 Visual Studio 中的“查找所有引用”仅限于相关变量