gpt4 book ai didi

c++ - 类型对齐会修改字体大小吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:50 24 4
gpt4 key购买 nike

我编写了以下代码并在 gcc 上进行了测试:

// firstly some platform-specific workarounds
#if _MSC_VER
#define ALN_BEGIN(x) __declspec(align(x))
#define ALN_END(x)
#define alignof(x) __alignof(x)
#else
#define ALN_BEGIN(x)
#define ALN_END(x) __attribute__((aligned(x)))
#define alignof(x) __alignof__(x)
#endif

// struct have three 4-byte members, but aligned at 32 byte
ALN_BEGIN(32) struct Foo
{
float a;
float b;
float c;
} ALN_END(32);

// show its size and alignment
int main(int argc, char** argv)
{
printf("size %d, alignment%d\n", sizeof(Foo), alignof(Foo));
}

当我使用 gcc 编译并运行时,虽然 Foo 的所有成员只有 12 个字节,但 sizeof(Foo) 得到 32,这是对齐大小。那么大小扩展是根据语言标准(这是可靠的)还是只是 GCC 的一个特性?

我正在创建一个对象池类,因此我必须精确处理类型大小和对齐方式。

最佳答案

是的,这符合标准。 sizeof (X) 基本上定义为数组中两个连续 X 对象的起始地址之间的字节偏移量。如果这些对象由于对齐限制而无法紧密跟随,则 sizeof 会相应增加。

引用 C++14, 5.3.3/2:

... When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. ... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

(强调我的)

关于c++ - 类型对齐会修改字体大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863272/

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