我试图通过派生类的移动构造函数显式调用基类的移动构造函数,但是,惊奇!,实际上调用了基类的复制构造函数而不是基类的移动构造函数。
我使用std::move()
函数来确保调用了派生类的移动构造函数!
代码:
class Base
{
public:
Base(const Base& rhs){ cout << "base copy ctor" << endl; }
Base(Base&& rhs){ cout << "base move ctor" << endl; }
};
class Derived : public Base
{
public:
Derived(Derived&& rhs) : Base(rhs) { cout << "derived move ctor"; }
Derived(const Derived& rhs) : Base(rhs) { cout << "derived copy ctor" << endl; }
};
int main()
{
Derived a;
Derived y = std::move(a); // invoke move ctor
cin.ignore();
return 0;
}
程序输出:
基类复制构造函数
派生类移动构造函数
如您所见,基类的移动构造函数被忘记了,那么我该如何调用它呢?
Derived y = Derived()
中,概念上调用了移动构造函数:右侧的对象无法被引用,即它不是左值。然而,大多数编译器可能会省略移动构造:如果编译器可以直接在正确的位置构造临时对象,则可以自由地不使用移动(或复制)构造,即使在省略构造函数时会有副作用(例如从构造函数或析构函数输出)。 - Dietmar KühlDerived(Derived&&) = default;
。但是,一旦你明确地将参数转发到Base()
构造函数,你就需要使用std::move()
(或等效物)。 - Dietmar Kühl