C++ 的继承成本

发布于 2024-09-08 03:01:35 字数 373 浏览 5 评论 0原文

以下面的代码片段为例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

维持三分热 2024-09-15 03:01:35

根据标准,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 twice sizeof(baz).

相对绾红妆 2024-09-15 03:01:35

是的,没有任何虚拟成员或成员变量,不应该有大小差异。

Yeah, without any virtual members or member variables, there shouldn't be a size difference.

错爱 2024-09-15 03:01:35

据我所知,如果需要任何优化,编译器会正确优化它。

As far as I know the compiler will optimize this correctly, if any optimizing is needed at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文