"Short A: 4" -- specifies the member variable of the number of digits
The following code is sometimes used in struct or class.
Struct s { Short A: 4; Short B: 6; Short C: 8; }; |
This is a property of struct and class. It specifies the number of digits of a variable while declaring the variable.
The short type is originally 16-bit on a 32-bit machine. But from the perspective of space saving, we think it is a waste to store 16-bit data. A four-bit variable is enough, what should I do?
Of course, we can add a colon and a number after the variable while declaring the variable, indicating that the variable only occupies so many digits. Note:The number cannot be greater than the number of digits of the original type..
Structure of this struct in memory (Boundary alignment problem)
Code |
Memory illustration |
Struct s { Short A: 4; Short B: 6; S () { A = 2; B = 4; } }; |
|
Struct s { Short A: 4; Short B: 6; Short C: 8; S () { A = 2; B = 4; C = 6; } }; |
|
We can see in the first code that the 6-bit data in the memory is B.Next4-bit data a storage, and is based onSmall Terminal. The result of sizeof (s) is 2.
In the second codeNoIt is stored next to B just now, because the CompilerByte alignmentThe attribute is determined. When the compiler finds that the 8-bit C is still stored next to B, the data willSpanTwo 2-byte blocks (the number of bytes is calculated based on the longest data type in the struct without special designation, also known as the natural logarithm), which does not satisfy the byte alignment.AbandonedThe black 0 space on the left of the figure starts to store data C from the next 2-byte block.Exchange Space for speed. The result of sizeof (s) is 4.
There are two methods for byte alignment. Apart from the natural interface, the other method is to specify the interface. · Use pseudoinstructions# Pragma pack (N), The compiler will followNByte alignment; · Use pseudoinstructions# Pragma pack ()To cancel the custom byte alignment. Note: If the value of N specified in # pragma pack (n) is greater than the size of the maximum member in the structure,Then it does not workThe struct is still bounded by members with the largest size. |
Have you said this today?