为什么 alignas(64) 不与 64 对齐

why alignas(64) not aligned with 64

为什么 alignas(64) 与 64 不对齐?例如:

struct alignas(32) st32
{
    float a;
    uint16_t b;
    uint64_t c;
};

struct alignas(64) st64
{
    float a;
    uint16_t b;
    uint64_t c;
};

int main()
{
    st32 x;
    st64 y;

    std::cout
        << "alignof(st32) = " << alignof(st32) << '\n'
        << "alignof(st64) = " << alignof(st64) << '\n'
        << "&st32 a: " << &x.a << '\n'
        << "&st32 b: " << &x.b << '\n'
        << "&st32 c: " << &x.c << '\n'
        << "&st64 a: " << &y.a << '\n'
        << "&st64 b: " << &y.b << '\n'
        << "&st64 c: " << &y.c << '\n'; 
}

结果是

alignof(st32) = 32
alignof(st64) = 64
&st32 a: 0x7ffc59fc9660
&st32 b: 0x7ffc59fc9664
&st32 c: 0x7ffc59fc9668
&st64 a: 0x7ffc59fc9680
&st64 b: 0x7ffc59fc9684
&st64 c: 0x7ffc59fc9688

为什么&st64 b: 0x7ffc59fc9684不是0x7ffc59fc9688,因为地址需要64位对齐,我们应该把0x7ffc59fc9684-0x7ffc59fc9688留空,下一个数据从0x7ffc59fc9688开始。

why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688

对齐结构不会影响结构子对象的对齐。封闭结构的地址是 64 字节对齐的,b 是 4 字节大小的 a 之后的第二个成员,因此预期 b 不是 64 字节对齐是合理的。

if alignas don't align the sub object, then what's the point of this syntax before struct.

重点是对齐 class 本身。例如,SIMD 指令有时需要这样做。

这会给你想要的东西:

struct alignas(64) st64
{
    float a;
    alignas(64) uint16_t b;
    uint64_t c;
};

输出:

alignof(st32) = 32
alignof(st64) = 64
&st32 a: 0x7ffe33498ae0
&st32 b: 0x7ffe33498ae4
&st32 c: 0x7ffe33498ae8
&st64 a: 0x7ffe33498b00
&st64 b: 0x7ffe33498b40
&st64 c: 0x7ffe33498b48