代码之家  ›  专栏  ›  技术社区  ›  Jorn Vernee

在匿名结构中包装灵活数组时MSVC结构布局会发生变化吗?

  •  1
  • Jorn Vernee  · 技术社区  · 6 年前

    我正在查看以下结构的布局信息 using godbolt :

    struct Foo1 {
        int size;
        void *data[];
    };
    
    struct Foo2 {
        int size;
        struct {
            void *data[];
        };
    };
    

    Foo1 Foo2 还是一样。据我所知,匿名嵌套结构的任何字段都只是“折叠”到父结构中。那么 食物2 结果应该和 .

    但是,由MSVC 19.16生成并在使用标志时显示的布局 /d1reportSingleClassLayoutFoo 不同之处:

    class Foo1  size(8):
        +---
     0  | size
        | <alignment member> (size=4)
     8  | data
        +---
    class Foo2  size(16):
        +---
     0  | size
        | <alignment member> (size=4)
        | <anonymous-tag> <alignment member> (size=8)
     8  | data
        | <alignment member> (size=7)
        +---
    

    食物2 是我的两倍大 Foo1 . 和 data

    -Wall :

    warning C4200: nonstandard extension used: zero-sized array in struct/union
    note: This member will be ignored by a defaulted constructor or copy/move assignment operator
    warning C4820: 'Foo1': '4' bytes padding added after data member 'Foo1::size'
    warning C4200: nonstandard extension used: zero-sized array in struct/union
    note: This member will be ignored by a defaulted constructor or copy/move assignment operator
    warning C4820: 'Foo2::<anonymous-tag>': '7' bytes padding added after data member 'Foo2::data'
    warning C4201: nonstandard extension used: nameless struct/union
    warning C4820: 'Foo2': '4' bytes padding added after data member 'Foo2::size'
    

    但这些似乎都不能解释布局上的差异,也不能暗示未定义的行为。此外,该文件也没有: Anonymous structs .

    warning C4200: nonstandard extension used: zero-sized array in struct/union
    warning C4201: nonstandard extension used: nameless struct/union
    

    “零尺寸阵列” 数据 size 字段抛出一个错误。

    Foo1 食物2

    1 回复  |  直到 6 年前
        1
  •  2
  •   1201ProgramAlarm    6 年前

    您的匿名结构是一种独特的类型。因此,它的大小不能为零,因此大小为1字节。 data 仍然具有零大小,但包含它的结构没有。

    推荐文章