通过移动派生类来构造基类

时间:2018-01-19 13:35:14

标签: c++ move

我有这个简化的代码示例:

class Base {
    Base() = default;
    Base(const Base& src) {
        // construct by copying src etc. - ok, legal even if src points to Derived object
    }

    Base(Base&& src) {
        // construct by moving src - stealing its resources, ok, it was invented for this, 
        // but.. what if src points to Derived object?
    }
};

class Derived : public Base {

};

void foo() {
    Derived derived;
    Base base_by_copy_constructor(derived); // legal, derived cannot be touched so nothing will be wrong
    Base base_by_move(std::move(derived)); // uu? what's gonna happen, part of derived object (Base class) was moved..
}

这种行为是否合适?这可能会导致奇怪的问题,因为基础部分od Derived对象实际上是“未初始化的”。 那么..我们应该避免从具有移动运算符的类派生,还是让我们的派生类抵制“移动”它的基础部分?

(当然 - 这只是一个例子,类没有数据,移动操作员不做任何事情,所以这里什么都不会出错。我问的是这样一个真实世界的例子..情况:))< / p>

1 个答案:

答案 0 :(得分:1)

它们对切片没有问题,这可以明确地和有意义地完成。

然而,在进行OO编程时,通常只有一个规则:不要让对象(或组件)外部的任何实体有可能破坏不变量。

因此,如果调用基类的成员或构造函数可能会破坏派生类在它与其基类之间建立的不变量,那么基类必须是私有的。 (您仍然可以公开不会使用MailItem

打破不变量的基础成员