多态性和私有数据成员

Polymorphism and private data members

首先我想澄清一下,这个问题与 Scott Meyers 的书 Effective C++(第 3 版)有关,特别是 item 22: declare data-members private

我基本上理解它,并且正在尝试将一些东西应用到我的代码中以开始练习它。但是我有一个案例,我不确定如何解决它。基本上我有一些抽象接口和一些继承,看起来像这样。

class abstractSystem {
    ...
protected:
    AbstractThing *_thing;
}

class DerivedSystem : public AbstractSystem {
    // inherits _thing so we can use it here.
}

然而,这与第 22 项不一致。我认为最好为派生的 class 提供一个到基础 class 的接口,这在很多情况下都很好用,但在这种情况下,由于多态性用于决定 _thing 我们将在 getter 中复制它,以便在派生系统中任何时候我们需要访问它时我们都需要复制它。

所以我猜这不太好,并且与 项目 28 保持一致:避免返回 "handles" 对象内部 我似乎无法弄清楚如何不复制 _thing:

class AbstractSystem {
protected:
    AbstractThing thing() { return *_thing; }
private:
    AbstractThing *_thing;
}

class DerivedSystem {
    // now we need to use thing() to access _thing implying copy
}

这是必须完成的方式吗?复制(如果经常这样做的话)是不是有点难以复制性能?

我想可能是我的设计有问题。

您可以return引用'thing':

protected:
    AbstractThing const& thing() { return *_thing; }

这样可以避免复制整个对象。