Understanding Class Size Determination in C
Determining the size of a C class at compile-time requires an understanding of data alignment principles. Each member within a class has a size and alignment requirement.
Size and Alignment Calculation Process
During compilation, the compiler initializes a running size (S) to zero and an alignment requirement (A) to one (byte). For each member in the class:
After processing all members, the final size of the class is determined. It is the value of S adjusted to be a multiple of the alignment requirement of the entire class (A).
Alignment Considerations
Example
The provided code demonstrates this process:
<code class="cpp">#include <xmmintrin.h> class TestClass1 { __m128i vect; }; // Size: 16 bytes class TestClass2 { char buf[8]; char buf2[8]; }; // Size: 16 bytes class TestClass3 { char buf[8]; __m128i vect; char buf2[8]; }; // Size: 48 bytes class TestClass4 { char buf[8]; char buf2[8]; __m128i vect; }; // Size: 32 bytes</code>
TestClass3, despite having the same members as TestClass1 and TestClass2, is larger (48 bytes) due to the alignment requirement of __m128i, which forces a 16-byte boundary. TestClass4, with a different data member ordering, has a different alignment and size (32 bytes).
The above is the detailed content of How Does Data Alignment Affect the Size of C Classes?. For more information, please follow other related articles on the PHP Chinese website!