1. 程式人生 > 實用技巧 >(四)c語言之位元組對齊方式

(四)c語言之位元組對齊方式

// 對齊原則:每一成員需對齊為後一成員型別的倍數

// 補齊原則:最終大小補齊為成員型別最大值的倍數
#include <iostream>
#include <memory>
#include <string>
using namespace std;

// 空類,考慮的是當我們宣告該型別的例項時候,它必須在記憶體中
// 有一定的空間,否則就是不存在的,導致無法使用這些例項
class A
{
        A() {};
};

// 虛擬函式的大小為4 位元組對齊
class B
{
        B() {};
        virtual void func() {};
};

/* 4位元組 int 4 4 short 2 4+2=6 6不是下一個位元組4的倍數,6+2=8 int 4 8+4=12 12是下一個位元組1的倍數 char 1 12+1=13 13補齊為4的倍數 */ struct C { int a; short b; int c; char d; }; /* 4位元組 int 4 4 是下一個位元組1的倍數 short 2 4+2=6 是下一個位元組1的倍數 char 1 6+1=7 不是下一個位元組4的倍數 7+1=8 int 4 8+4=12 是4的倍數
*/ struct D { int a; short b; char c; int d; }; int main() { cout<<"class: "<<sizeof(A)<<endl; cout<<"class: "<<sizeof(B)<<endl; cout<<"struct: "<<sizeof(C)<<endl; cout<<"struct:
"<<sizeof(D)<<endl; return 0; }