在C ++中,我应该几乎总是使用虚拟继承吗? [英] In C++, should I almost always use virtual inheritance?

查看:82
本文介绍了在C ++中,我应该几乎总是使用虚拟继承吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此条目中看到,虚拟继承会增加sizeof(pointer)到对象的内存占用量.除此之外,仅在默认情况下使用虚拟继承以及仅在需要时使用常规继承对我有任何弊端吗?看来这会导致更多面向未来的类设计,但也许我错过了一些陷阱.

I see from this entry 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.

推荐答案

缺点是

  1. 所有类都必须始终初始化其所有虚拟基数(例如,如果A是B的虚拟基数,而C衍生自B,则它也必须初始化A本身).
  2. 在使用static_cast的任何地方都必须使用更昂贵的dynamic_cast(可能是问题,也可能不是问题,这取决于您的系统以及设计是否需要).
  1. All classes will have to initialize all its virtual bases all the time (e.g. if A is virtual base of B, and C derives from B, it also have to initialize A itself).
  2. You have to use more expensive dynamic_cast everywhere you use a static_cast (may or may not be the issue, depending on your system and whether your design requires it).

仅凭第1点就不值得了,因为您无法隐藏虚拟基础.几乎总是有更好的方法.

Point 1 alone makes it not worth it, since you can't hide your virtual bases. There is almost always a better way.

这篇关于在C ++中,我应该几乎总是使用虚拟继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆