为什么打包对象的 sizeof 低于预期?
Why is the sizeof for a packed object lower than anticipated?
我有以下代码:
#pragma pack(push, 4)
class C {
public:
char a;
char b;
short c;
char d;
};
C e;
我不明白为什么 sizeof(e)
是 6。
我认为 sizeof(e)
将是 8 => 1(a) + 1(b) + 2(c) + 1(d) + 3(对齐)
打包指令设置对齐的上限,而不是最小值。 C
的对齐要求只有2,因此将对齐上限降低到4对其没有影响。
如果你打算增加对齐,你可以使用 alignas
代替(这恰好是一个标准功能,与打包不同)。
but still, why the padding is to number divide by 2 and not power of 2?
因为对象的大小只需要是该对象的对齐方式的倍数。就是那个对齐必须是2的幂。
我有以下代码:
#pragma pack(push, 4)
class C {
public:
char a;
char b;
short c;
char d;
};
C e;
我不明白为什么 sizeof(e)
是 6。
我认为 sizeof(e)
将是 8 => 1(a) + 1(b) + 2(c) + 1(d) + 3(对齐)
打包指令设置对齐的上限,而不是最小值。 C
的对齐要求只有2,因此将对齐上限降低到4对其没有影响。
如果你打算增加对齐,你可以使用 alignas
代替(这恰好是一个标准功能,与打包不同)。
but still, why the padding is to number divide by 2 and not power of 2?
因为对象的大小只需要是该对象的对齐方式的倍数。就是那个对齐必须是2的幂。