C++位元組對齊
阿新 • • 發佈:2021-08-30
- 變數的首地址能夠被其對齊位元組數大小整除。(實際開發中可以無視這條)
- 每個成員相對首地址的偏移量都是該成員大小的整數倍,如果不是,那麼前一個成員變數補齊
- 總大小是最大成員大小的整數倍
1 #include <iostream> 2 using namespace std; 3 4 struct POINTER 5 { 6 void* ptr; 7 }; 8 9 struct A 10 { 11 char a; 12 }; 13 14 struct B 15 { 16 char a; 17 charView Codeb; 18 }; 19 20 struct C 21 { 22 char a; 23 int b; 24 long c; 25 }; 26 27 struct D 28 { 29 long c; 30 char a; 31 int b; 32 }; 33 34 struct E 35 { 36 char a; 37 long c; 38 int b; 39 }; 40 41 struct F 42 { 43 char a; 44 long c; 45char b; 46 }; 47 48 struct G 49 { 50 char a; 51 long c; 52 F b; 53 }; 54 55 struct H 56 { 57 char a; 58 char b; 59 short c; 60 }; 61 62 struct I 63 { 64 char a; 65 char b; 66 int c; 67 }; 68 69 struct EMPTY_CLASS 70 { 71 }; 72 73struct EMPTY_CLASS_WITH_VIRTUAL 74 { 75 virtual ~EMPTY_CLASS_WITH_VIRTUAL(){} 76 }; 77 78 #define CALC_STRCUT_SIZE(T) \ 79 std::cout <<"size of type " << #T << " is " << sizeof(T) << std::endl; 80 81 int main(int argc, char** argv) 82 { 83 printf("sizeof(long) : %d\n", sizeof(long)); 84 CALC_STRCUT_SIZE(A) 85 CALC_STRCUT_SIZE(B) 86 CALC_STRCUT_SIZE(C) 87 CALC_STRCUT_SIZE(D) 88 CALC_STRCUT_SIZE(E) 89 CALC_STRCUT_SIZE(F) 90 CALC_STRCUT_SIZE(G) 91 CALC_STRCUT_SIZE(H) 92 CALC_STRCUT_SIZE(I) 93 94 CALC_STRCUT_SIZE(EMPTY_CLASS) 95 CALC_STRCUT_SIZE(EMPTY_CLASS_WITH_VIRTUAL) 96 97 CALC_STRCUT_SIZE(char*) 98 CALC_STRCUT_SIZE(short*) 99 CALC_STRCUT_SIZE(int*) 100 CALC_STRCUT_SIZE(long*) 101 CALC_STRCUT_SIZE(void*) 102 CALC_STRCUT_SIZE(F*) 103 CALC_STRCUT_SIZE(POINTER) 104 return 0; 105 }