gpt4 book ai didi

c++ - 通过 move 派生类来构造基类

转载 作者:太空狗 更新时间:2023-10-29 22:56:23 25 4
gpt4 key购买 nike

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

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..
}

这样的行为合适吗?这可能会导致奇怪的问题,因为 Base 部分 od Derived 对象实际上已“取消初始化”。所以.. 我们应该避免派生自具有 move 运算符的类,还是让我们的派生类抵抗“move ”其基础部分?

(当然 - 这只是示例,类没有数据, move 运算符不做任何事情,所以这里不会出错。我问的是这种情况的真实示例:))

最佳答案

他们的切片没有问题,这可以明确和intensionnaly完成。

然而,一般来说,在进行 OO 编程时,只有一条规则需要遵循:不要让对象(或组件)外部的任何实体有机会破坏不变量。

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

关于c++ - 通过 move 派生类来构造基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com