我应该几乎总是使用虚拟继承吗?
我从 虚拟继承不会破坏静态组合? 中看到,虚拟继承添加了 sizeof(pointer)
对象的内存占用。除此之外,默认情况下使用虚拟继承,仅在需要时才使用传统继承对我来说有什么缺点吗?看起来它会带来更多面向未来的类设计,但也许我错过了一些陷阱。
I see from Virtual inheritance doesn't break static composition? that virtual inheritance adds sizeof(pointer)
to an object's memory footprint. Other than that, are there any drawbacks to me just using virtual inheritance by default, and conventional inheritance only when needed? It seems like it'd lead to more future-proof class design, but maybe I'm missing some pitfall.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
缺点是
static_cast
的任何地方,您都必须使用更昂贵的dynamic_cast
(这可能是也可能不是问题,具体取决于您的系统以及您的设计是否需要它)。仅第一点就让它不值得,因为你无法隐藏你的虚拟基地。几乎总有更好的方法。
The drawbacks are that
dynamic_cast
everywhere you use astatic_cast
(may or may not be the issue, depending on your system and whether your design requires it).Point 1 alone makes it not worth it, since you can't hide your virtual bases. There is almost always a better way.
根据我的经验,几乎从来不需要虚拟继承(与虚拟方法相反)。在 C++ 中,它用于解决“钻石继承问题”,如果避免多重继承,实际上就不会发生这种情况。
我很确定我从未在 C++ 书籍之外遇到过虚拟继承,其中包括我编写的代码和我维护的数百万行系统。
In my experience, virtual inheritance (as opposed to virtual methods) is almost never needed. In C++ it's used to address the "diamond inheritance problem", which if you avoid multiple inheritance cannot actually happen.
I'm pretty sure that I've never encountered virtual inheritance outside C++ books, which includes both code I write and million+ line systems I maintain.