空白類別(無非靜態資料成員)大小為 1 byte。組合空白類別會因對齊導致外層類別體積膨脹;私有繼承空白類別可讓編譯器最佳化為 0 大小(EBO)。
/*************************************************
File: test.cpp
Copyright: C.L.Wang
Author: C.L.Wang
Date: 2014-04-11
**************************************************/
#include <iostream>
using namespace std;
class Empty {};
class HoldsAnInt { private: int x; Empty e; };
class HoldsAnIntP : private Empty { private: int x; };
int main() {
cout << "Int : " << sizeof(int) << endl;
cout << "HoldsAnInt(class) : " << sizeof(HoldsAnInt) << endl;
cout << "HoldsAnIntP(inheritance) : " << sizeof(HoldsAnIntP) << endl;
return 0;
}
Int : 4
HoldsAnInt(class) : 8
HoldsAnIntP(inheritance) : 4
Empty e 佔 1 byte,int x 4 bytes,對齊至 8 bytes。int x(4 bytes)。std::allocator、std::function、std::tuple 的空白基類別)。