A /C + + data alignment Rollup
here are two sentences to summarize the principle of data alignment:
(1) for n-byte elements (n=2,4,8,... ), its first address can be divisible by n, the ability to obtain the best performance;
(2) If Len is the longest variable in the struct, size is the number of bits in the CPU (processor), the alignment rule:
- If Len < size, align in Len
- If Len >= size, align in size
The case of specifying alignment is not considered here.
Test
struct B{bool i;int j;bool k;}; |
struct A{int j;bool i;bool k;}; |
Cout<<sizeof (B) <<endl;cout<<sizeof (A) <<endl; |
| Output results: 12 8 |
It is not difficult to understand, under normal circumstances. The address bus is always in accordance with the address of the alignment after the interview. For example, if you want to get the 4-byte content from 0x0000 0001, the system starts with 0x0000 0000, obtains a 4 byte, and then removes three bytes from it. Then start with 0x0000 0004, take out a four byte, then take out a byte, two times to combine what you want to get, but assume that the initial address starts out as 0x0000 0000 then just once. so for B, by four-byte alignment if the address of I is 0x0000 0000 then in order to remove J at one time then the address of J must be 0x0000 0004, because four-byte alignment K also accounts for four bytes. And a If the address of J is 0x0000 0000, then I is 0x0000 0004 is very reasonable, and when the K address is 0x0000 0002, the same can be removed once, so altogether 8 bytes.
for sizeof there is a need to pay attention to the place:
struct C{int a;static int b;}; Cout<<sizeof (C) <<endl.
|
Results: 4 Explanation: Since the static variable is stored in the global zone, the size allocated in the sizeof calculation stack is not counted, and the total result is 4. |
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
A/C + + data alignment Rollup