You can reduce the size of classes and structs simply by rearranging data members' order.
Consider the following unoptimized class declaration:
}; //sizeof (C) equals 12
The cumulative size of C's members is 1+4+1 bytes, and yet the sizeof this class is twice as big. The extra six bytes are wasted as padding bytes which the compiler inserts between after each data member whose size isn't divisible by 4. Thus, three padding bytes are inserted after the member a, and three more padding bytes are appended after c.
You can reduce the layout of this class by declaring all small data members first, and move the larger data members to the end:
}; // sizeof (B) equals 8
This time, the compiler inserted only 2 padding bytes after the member c. Because b occupies 4 bytes, it naturally aligns on a word boundary without necessitating additional padding bytes.
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.