Do you know the sizes of these things in real memory?

It costs less time for CPU to read data from memory or write data into memory if the address of the data is divisible by the size of the data. So if there is an int stored in address "0", then a double next to it will be stored in address "8", because the size of double is 8 bytes. Since the size of int is only 4 bytes, there are 4bytes wasted between these two valid numbers. What about a struct or a class (in C++, struct is almost the same as class)? The rule is the same. Additionally, to achieve address alignment, the size of a class must be divisible by the size of the biggest element. Let's take a test.

#include <iostream>
using namespace std;

class CA
{
    
double d;
    
char c;
    
int i;
}
;

int main()
{
    cout
<<sizeof(char)<<" "<<sizeof(int)<<" "<<sizeof(double)<<endl;
    cout
<<sizeof(CA)<<endl;
    
return 0;
}

It will print:

1 4 8

16

That is easy to understand according to the rule. First, the double element is stored in the beginning of the block, and we suppose its address is 0 (offset ). Then a char is stored in the address 8, which is divisible by 1. At last is the int element. Its address is 12, not 9, because it should be divisible by 4. So the total size of this class is 16, i.e. 8 + 1 + 3(invalid bytes, in order to make the total size be divisible by 8) + 4.

Then what about changing the order of the three elements like this?

class CB
{
    
char c;
    
double d;
    
int i;
}
;

The size of the whole class is 24, not 16. Let's see why it is changed. First, a char is stored in address 0. Then comes a double. It will be stored in address 8 because of the rule. So the next int will be stored in address 16. Now the total size is 1 + 7(invalid bytes) + 8 + 4 = 20. But 20 cannot be divisible by 8. To achieve address alignment, the compiler adds another 4 invalid bytes to the end of the block, so 24 is printed.

This experiment is executed with Microsoft Visual C++ compiler. If we compile it with g++ in Linux, the sizes of both classes will be 16, 16. In the second case, g++ compiler will store the int element into the address 4, because from 4 to 7, there is enough space to store an int. And this can save 8 bytes of memory. So g++ is more optimized in arranging data in memory.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章