联合中的填充是否存在 [英] Padding in union is present or not

查看:11
本文介绍了联合中的填充是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我想知道union是否使用padding?
既然union的大小是最大的数据成员大小,那么最后可以padding吗?

Hello all,
I want to know whether union uses padding?
since the size of union is the largest data member size, can there be padding at the end?

推荐答案

因为union的大小是最大的数据成员大小

since the size of union is the largest data member size

这不一定是真的.考虑

union Pad {
    char arr[sizeof (double) + 1];
    double d;
};

该联合的最大成员是arr.但通常,double 会以四字节或八字节的倍数对齐(取决于double 的架构和大小).在某些架构上,这甚至是必要的,因为它们根本不支持未对齐的读取.

The largest member of that union is arr. But usually, a double will be aligned on a multiple of four or eight bytes (depends on architecture and size of double). On some architectures, that is even necessary since they don't support unaligned reads at all.

所以sizeof(union Pad)通常大于sizeof(double)+1[通常16 = 2 * sizeof(double)在 64 位系统上,16 位或 12 位在 32 位系统上(在具有 8 位 char 和 64 位 double 的 32 位系统上,需要double 的对齐方式可能仍然只有四个字节)].

So sizeof (union Pad) is usually larger than sizeof (double) + 1 [typically 16 = 2 * sizeof (double) on 64-bit systems, and either 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit char and 64-bit double, the required alignment for double may still be only four bytes)].

这意味着联合中必须有填充,而且只能放在最后.

That means there must then be padding in the union, and that can only be placed at the end.

通常,union 的大小将是任何不小于最大成员的成员所需的最大对齐的最小倍数.

Generally, the size of a union will be the smallest multiple of the largest alignment required by any member that is not smaller than the largest member.

这篇关于联合中的填充是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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