空白基类最优化(EBO empty base optimization 或 EBCO empty base class optimization)空类作为类成员是按照类内字节对齐方式占据内存,作为继承基类时在子类中占据字节被优化为0。
EBCO参考https://en.cppreference.com/w/cpp/language/ebo。
- mingw32环境下的EBO
1
2
3
4
5// empty base optimization applies
struct Base {}; // empty class 1 Bytes
struct Derived1 : Base { // 4 Bytes
int i;
}; - 如果空基类也是第一个非静态数据成员的类型或类型的基类,则禁止进行空基优化,因为同一类型的两个基子对象需要在最派生类型的对象表示中具有不同的地址。
1
2
3
4
5
6
7
8// empty base optimization does not apply,
// base occupies 1 byte, Base member occupies 1 byte
// followed by 2 bytes of padding to satisfy int alignment requirements
// | Base 1 Byte | Base 1 Byte | 2 Bytes | i 4 Bytes |
struct Derived2 : Base { // 8 Bytes
Base c; // Base, occupies 1 byte, followed by padding for i
int i;
};1
2
3
4
5
6
7
8
9
10// empty base optimization does not apply,
// base takes up at least 1 byte plus the padding
// to satisfy alignment requirement of the first member (whose
// alignment is the same as int)
// | Base 1 Byte | 3 Bytes | c 4 Bytes | i 4 Bytes |
struct Derived3 : Base { // 12 Bytes
Derived1 c; // derived from Base, occupies sizeof(int) bytes
int i;
}; - 多继承,继承链中只要满足第一个非静态数据成员的类型或类型的基类不是空基类,照样进行空基优化。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class EmptyClass1{};
class EmptyClass2{};
class Derived1: public EmptyClass1{ // 4 Bytes
private:
int x1;
};
class Derived2: public EmptyClass1, public EmptyClass2{ // 4 Bytes
private:
int x2;
};
class Derived3: public Derived1{ // 8 Bytes
private:
int x3;
};
class Derived4: public Derived2{ // 8 Bytes
private:
int x4;
};