+ 1
C++ - Unexpected class size
In this code, there are 3 classes, one has an integer as it's only data member, one has a character, and one has both. When I print the sizes of these classes, the first two show 4 and 1 respectively. But the third one shows 8, shouldn't it be (4+1=)5? When I change the members to either both integers or both characters, the output is as expected(8 and 2 respectively). Can anyone please tell why the class "BothIntAndChar" has unexpected size? https://code.sololearn.com/ceskya25VO11/?ref=app
6 Respostas
+ 4
Padding, the compiler is aligning the size of the class to a multiple of 4 because of the integer, as the integer’s address needs to be aligned to a multiple of 4 for efficiency. The next multiple of 4 is 4*2, which is 8, so the compiler adds 3 bytes of padding after the char to ensure the structure is 4 bytes aligned.
+ 3
I believe it has to do with how the compiler "lines up" the variable boundaries. It's probably more efficient to have 2 4 byte buffers instead of 1 4 byte buffer and 1 1 byte buffer.
+ 1
The efficiency comes from the fact that modern processors use cache lines that are a power of 2 to read and write memory (typically 64 bytes in length). If the addresses were not naturally aligned it would require two cache lines (128 bytes) instead of one when the data falls in between two cache line boundaries, which will hurt performance.
0
@aklex Thanks, you said a multiple of 4 due to efficiency, would you please explain what is "efficiency" here(better if you can give an example)?