可以包裹在结构造成额外的填充类型? [英] Can wrapping a type in a struct cause additional padding?

查看:125
本文介绍了可以包裹在结构造成额外的填充类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  用一个单一的元素结构尺寸

由于任何类型的 A 和下面的结构:

Given any type A and the following struct:

struct S
{
    A a;
};

是否有任何情况下,的sizeof(S)更大的sizeof(A)

例如,可以通过的sizeof(的std ::阵列< T,N>)的sizeof更大(T [N])

推荐答案

虽然结构可以填充,在我知道所有的系统中,编译器会垫,使结构的排列相同的最大对准其成员。它这样做,使得结构的阵列将总是被正确地对齐。

While the struct can be padded, on all systems I know, the compiler will pad so that the alignment of the structure is the same as the largest alignment of its members. It does this so that an array of the structure will always be correctly aligned.

所以:

struct S 
{
   char a;
} // Size 1, no padding

struct S2 
{
   unsigned int a;
   char b;
} // Size 8, 3 bytes padding (assuming 32 bit integer)

编辑:请注意,编译器还可以添加内部填充,以保持数据的比对正确

Note, that compilers can also add internal padding, to keep the alignment of the data correct.

在C / C ++标准没有规定这些细节。你想要什么是C ABI(应用程序二进制接口)为您所运行应指定结构默认布局系统,(编译器可以选择覆盖此,如果他们认为合适,也见的#pragma包)。举一个例子,看一下 X86_64 ABI 13页,其中规定:

The C/C++ standard doesn't specify any of these detail. What you want is the C ABI (application binary interface) for the system you're running on, which should specify default layout for structs (compilers can choose to override this if they see fit, see also #pragma pack). For an example, look at the X86_64 ABI page 13, which states:

聚合和联合结构和联合承担的对齐方式
  他们最严格对齐的分量。每个成员被分配给
  最低可用与相应的对准的偏移。尺寸
  任何对象始终是该对象的取向的倍数。数组
  使用相同的取向作为其元素,除了局部或全局
  的长度为至少16个字节数组变量或C99可变长度
  数组变量总是具有至少16字节对齐。结构体
  和工会的对象可能需要填充,以满足大小和对齐
  约束。任何填充的内容理解过程网络定义。

Aggregates and Unions Structures and unions assume the alignment of their most strictly aligned compo- nent. Each member is assigned to the lowest available offset with the appropriate alignment. The size of any object is always a multiple of the object‘s alignment. An array uses the same alignment as its elements, except that a local or global array variable of length at least 16 bytes or a C99 variable-length array variable always has alignment of at least 16 bytes. Structure and union objects can require padding to meet size and alignment constraints. The contents of any padding is undefined.

这篇关于可以包裹在结构造成额外的填充类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆