since the size of union is the largest data member size
That need not be true. Consider
union Pad {
char arr[sizeof (double) + 1];
double d;
};
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.
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…