C++ 的继承成本
以下面的代码片段为例:
struct Foo
{
typedef int type;
};
class Bar : private Foo
{
};
class Baz
{
};
如您所见,此关系中不存在虚函数。既然是这种情况,那么就语言而言,以下假设是否准确?
Bar
中不会创建虚函数表。sizeof(Bar) == sizeof(Baz)
基本上,我试图弄清楚我是否会为此付出任何形式的惩罚。我的初始测试(尽管是在单个编译器上)表明我的断言是有效的,但我不确定这是否是我的编译器的优化器或负责我所看到内容的语言规范。
Taking the following snippet as an example:
struct Foo
{
typedef int type;
};
class Bar : private Foo
{
};
class Baz
{
};
As you can see, no virtual functions exist in this relationship. Since this is the case, are the the following assumptions accurate as far as the language is concerned?
- No virtual function table will be created in
Bar
. sizeof(Bar) == sizeof(Baz)
Basically, I'm trying to figure out if I'll be paying any sort of penalty for doing this. My initial testing (albeit on a single compiler) indicates that my assertions are valid, but I'm not sure if this is my compiler's optimizer or the language specification that's responsible for what I'm seeing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据标准,Bar不是POD(普通旧数据)类型,因为它有一个基数。因此,该标准为 C++ 编译器提供了广泛的自由度来处理此类类型。
然而,很少有编译器会在这里做任何疯狂的事情。您可能需要注意的一件事是空基优化。由于各种技术原因,C++ 标准要求为任何实例分配存储空间。对于某些编译器,Foo 将在
bar
类中分配专用空间。然而,实现空基优化的编译器(大多数在现代使用中)将删除空基。如果给定的编译器未实现 EBO,则
sizeof(foo)
将至少是sizeof(baz)
的两倍。According to the standard, Bar is not a POD (plain old data) type, because it has a base. As a result, the standard gives C++ compilers wide latitude with what they do with such a type.
However, very few compilers are going to do anything insane here. The one thing you probably have to look out for is the Empty Base Optimization. For various technical reasons, the C++ standard requires that any instance be allocated storage space. For some compilers, Foo will be allocated dedicated space in the
bar
class. Compilers which implement the Empty Base Optimization (most all in modern use) will remove the empty base, however.If the given compiler does not implement EBO, then
sizeof(foo)
will be at least twicesizeof(baz)
.是的,没有任何虚拟成员或成员变量,不应该有大小差异。
Yeah, without any virtual members or member variables, there shouldn't be a size difference.
据我所知,如果需要任何优化,编译器会正确优化它。
As far as I know the compiler will optimize this correctly, if any optimizing is needed at all.