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

MSVC struct layout changes when wrapping flexible array in anonymous struct?

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

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

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

我希望结构 Foo1Foo2 的布局相同。据我了解,匿名嵌套结构的任何字段都只是 "folded" 到父结构中。所以 Foo2 的布局应该与 Foo1.

的布局相同

但是,由 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)
    +---

Foo2Foo1 的两倍。而data突然好像有1个字节的大小。

-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'

但是其中 none 似乎解释了布局上的差异,或者暗示了未定义的行为。而且,文档也没有:Anonymous structs.

郑重声明,我知道这段代码依赖于 MSVC 扩展:

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

"zero-sized array" data 似乎是一个灵活的数组成员,因为将它放在 size 字段之前会引发错误。

为什么 Foo1Foo2 的布局不同?

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