SizeOf and Alignment (alignment)
1: ALIGNMENT definition alignment means that the object's start address must meet the conditions: >> # Pragma Pack (Push, 1) << any address
>> # Pragma Pack (Push, 2) << Even Address
>> # Pragma Pack (Push, 4) << address must be a multiple of 4
>> # Pragma Pack (Push, 8) << address must be a multiple of 8
2: Basic Type T Alignment (T) alignment is 1, 2, 4, 8 mentioned above
Now correspond to each type T, there is an alignment (t) and t corresponding to this correspondence:
(The following is for the compiler we have encountered now) << char -> 1 (always 1)
<< Short #pragma Pack (1) -> 1 #pragma pack (2) -> 2 #pragma pack (4) -> 2 // Oh, here is the key ... -> 2
<< int #pragma pack (1) -> 1 #pragma pack (2) -> 2 #pragma Pack (4) -> 4 // Oh, here is the key ... -> 4 ... Here is a concept, we are still named INTERNAL_PACK (T): Internal_Pack (char) = 1 INTERNAL_PACK (SHORT) = 2 INTERNAL_PACK (int) = 4 INTERNAL_PACK (INT64) = 8 ... and current compiler Norning to alignment.
Compile its current #pragma pack (n) value we named Pack (= n)
Then we have a formula: IF (Internal_Pack (T) The following is true for any type of T: Alignment (T) <= PACK ---------------------------------------------------------------------------------- 1 3 struct (or class) Type St Alignment (ST) Alignment (st) = max {alignment (t) | T is the Type of Data MEMBER of ST} 4 examples << #pragma pack (1) struct a {....}; all alignment (Type) 1 by # 1, in Pack (1) << #pragma pack (4) struct a {char ch; short sh;}; alignment (ch) = 1 alignment (sh) = 2 alignment (a) = 2 << #pragma Pack (8) Struct a {char ch; int N; char ch;}; alignment (n) = 4 alignment (a) = 4 << #pragma pack (2) struct a {char ch; int N CHAR CH;}; alignment (n) = 2 alignment (a) = 2 5: SIZEOF (T) << For basic types, SIZEOF (T) = INTERNAL_PACK (T) << The structure of the last data member M_Last is called ST ~ SIZEOF (ST) = Sizeof (ST ~) LAST_SIZE PATCH where << Last_Size = MEMBER_PATCH SIZEOF (M_LAST) MEMBER_PATCH = [SIZEOF (ST ~) is smaller than its alignment (m_last) multiples]; << patch = [SIZEOF (ST ~ ) last_size to the minimum distance of Alignment (ST) multiple) Where << MEMBER_PATCH is because M_LAST to Align Alignment (m_last) << Patch is because if a array is declared: ST [2]; in order to meet 1: ST [1] address alignment (st) aligned 2: Sizeof (ST ) = sizeof (ST1) sizeOf (ST2) The key is the second article, so it is necessary to Patch to make the remaining space.