"Inheriting" 移动运算符?

"Inheriting" Move Operators?

我正在观看 Bjarne Stroustrup 的演讲,该部分介绍移动运算符及其优势。

他提到 here 显式移动构造函数,例如:

Matrix(Matrix&& a)
{
    rep = a.rep;
    a.rep = {};
}

是"c-style"和"cryptic".

然后他接着说,在很多情况下,写copy/move运算符是可以避免的;他提供了以下示例 here:

class Matrix
{
    vector<double> elem;
    // ... matrix access...
}

他说这个矩阵 class "inherits" 资源管理来自 vector 并且 copy/move 构造函数是隐式生成的。

有人可以帮忙澄清一下他的意思吗?如果我没有为 Matrix 定义移动运算符,我将如何获取 Matrix 对象并利用移动语义?

移动构造函数在

时隐式定义
  • X does not have a user-declared copy constructor,
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator,
  • X does not have a user-declared destructor, and
  • the move constructor would not be implicitly defined as deleted.

所以在 Matrix 的情况下,移动构造函数是隐式定义的。并且隐式移动构造函数尽最大努力移动它的数据成员。 std::vector 是可移动的,所以它移动了 Matrix 结构中的向量实例。

因为 std::vector 是一个已经实现此功能的 class。通过将其用作 Matrix 的存储空间,当您要玩弄 Matrix 及其数据时,std::vector 将参与进来,将我上面提到的功能带入游戏。