空基类优化(EBO)

c++ 有些类是空的,这意味着这些类应该只包含类型成员、非虚函数或静态成员函数,只要存在非静态成员函数、虚函数、虚基类则意味着非空。对于空类,它的大小是 0 吗?NO, 实际它的占用了一个字节。

空基类优化(Empty Base Optimization, EBO)是 C++ 中的一个技术,用于优化包含空基类)的类的内存布局。在 C++ 标准中,任何非空对象都必须有一个独一无二的地址,但如果一个类没有任何数据成员,它占用的内存可以被优化掉。

要测试空基类优化(EBO),我们可以编写一些简单的 C++ 代码来比较使用和不使用 EBO 时类的大小。这可以帮助我们理解 EBO 如何减少内存占用。

#include <iostream>

class EmptyBase {};

class NonEmptyBase {
    int data;
};

class DerivedFromEmpty : public EmptyBase {
    int data;
};

class DerivedFromNonEmpty : public NonEmptyBase {
    int data;
};

class CombinedFromEmpty1 {
    EmptyBase base;
    int data;
};

class CombinedFromEmpty2 {
    [[no_unique_address]] EmptyBase base;
    int data;
};

int main() {
    std::cout << "Size of EmptyBase: " << sizeof(EmptyBase) << std::endl; //1
    std::cout << "Size of NonEmptyBase: " << sizeof(NonEmptyBase) << std::endl; //4
    std::cout << "Size of DerivedFromEmpty: " << sizeof(DerivedFromEmpty) << std::endl; //4
    std::cout << "Size of DerivedFromNonEmpty: " << sizeof(DerivedFromNonEmpty) << std::endl; //8

    std::cout << "Size of CombinedFromEmpty1: " << sizeof(CombinedFromEmpty1) << std::endl; //8
    std::cout << "Size of CombinedFromEmpty2: " << sizeof(CombinedFromEmpty2) << std::endl; //4

    return 0;
}

代码示例链接

打赏作者