gpt4 book ai didi

c++ - 32 位平台上结构中的 alignas

转载 作者:可可西里 更新时间:2023-11-01 17:56:41 25 4
gpt4 key购买 nike

在 32 位 x86 linux 上运行以下代码时,我得到了意想不到的结果(编译器标志:g++ -std=c++14 -m32)。我试过 gcc 和 clang。

#include <iostream>
using namespace std;

struct S1
{
uint64_t a;
uint32_t b;
};

struct S2
{
alignas(uint64_t) char a[8];
uint32_t b;
};

int main()
{
cout << "sizeof(S1)=" << sizeof(S1) << endl;
cout << "sizeof(S2)=" << sizeof(S2) << endl;
}

输出是:

sizeof(S1)=12
sizeof(S2)=16

这里发生了什么?为什么 S1 和 S2 的大小不同?据我了解,64 位整数值在 32 位 x86 机器上与 32 位对齐。这确实解释了为什么 S1 的大小是 12 个字节。但为什么这不适用于 S2?

最佳答案

alignof 关键字衡量一个类型作为一个完整对象的对齐方式;即当它被分配为单个对象或数组元素时。这不一定与该类型作为子对象的对齐要求相同; Are members of a POD-struct or standard layout type guaranteed to be aligned according to their alignment requirements?

结构中 64 位整数的对齐由 x386 ABI 规定为 4 字节; gcc 不能随意更改它,因为它会破坏与其他目标文件和程序的二进制兼容性。但是,它可以将完整对象 64 位整数对齐到 8 个字节,因为这样做不会影响 ABI,并且可以更有效地访问内存。

关于c++ - 32 位平台上结构中的 alignas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com