将默认构造函数添加到基类会更改sizeof()派生类型 [英] Adding a default constructor to a base class changes sizeof() a derived type

查看:163
本文介绍了将默认构造函数添加到基类会更改sizeof()派生类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于认为我对C ++内部和内存布局有很好的把握,但这个让我感到困惑。我有以下测试代码:

I tend to think I have a pretty good grasp of C++ internals and memory layouts, but this one has me baffled. I have the following test code:

#include <stdio.h>

struct Foo
{
    //Foo() {}
    int x;
    char y;
};

struct Bar : public Foo
{
    char z[3];
};

int main()
{
    printf( "Foo: %u Bar: %u\n", (unsigned)sizeof( Foo ), (unsigned)sizeof( Bar ) );
}

输出合理:


Foo:8 Bar:12

Foo: 8 Bar: 12

然而,这是非常奇怪的部分,如果我取消注释Foo()上的简单默认构造函数,sizeof(Bar)发生了变化!如何添加ctor可能会改变这些类的内存布局?

However, this is the very odd part, if I uncomment that simple default constructor on Foo(), the sizeof( Bar ) changes! How can the addition of a ctor possibly change the memory layout of these classes?


Foo:8 Bar:8

Foo: 8 Bar: 8

使用gcc-7.2编译

Compiled using gcc-7.2

推荐答案

GCC遵循Itanium ABI for C ++,它阻止POD的尾部填充用于存储派生类数据成员。

GCC follows the Itanium ABI for C++, which prevents the tail-padding of a POD being used for storage of derived class data members.

添加用户提供的构造函数意味着 Foo 不再是POD,因此该限制不适用于 Bar

Adding a user-provided constructor means that Foo is no longer POD, so that restriction does not apply to Bar.

有关ABI的详细信息,请参阅此问题

这篇关于将默认构造函数添加到基类会更改sizeof()派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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