考虑这段代码:
// T is *any* type
struct str_T{
T a, b;
};
我知道(几乎总是)在具有不同对齐方式的对象之间存在填充,因为两个成员都是 T
类型。但这一次没有不同的对齐方式。这个断言总能通过吗?
static_assert(sizeof(str_T) == 2 * sizeof(T));
// i.e. padding-free
最佳答案
不,这不能保证。 编译器总是可以决定填充或不填充结构成员之间的额外位。 (除非被覆盖)
引自C11 draft , 6.7.2.1 结构和 union 说明符
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning
关于c - 是否保证相同类型的值之间没有填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545575/