Site Tools


wiki:cpp-empty-base-optimization

C++ Empty base optimization

Empty base optimization (EBO) is a compiler technique where an empty base class takes no space in the derived object. Since an empty class has size 1 (to give it a unique address), deriving from it would normally add 1 byte to the derived object; EBO allows the derived object to have the same size as if the base didn't exist.

Prefer using [[no_unique_address]] (C++20) or composition over inheritance for empty types to clarify intent and enable optimization.

Example

This example shows EBO reducing object size when inheriting from empty classes.

// compile: g++ -std=c++20 -o ebo ebo.cpp
// run: ./ebo
// description: empty base optimization reduces object size
 
#include <iostream>
 
class Empty {};
 
class WithEBO : Empty {
public:
    int value;
};
 
class NoEBO : public Empty {
public:
    int value;
};
 
class Modern {
public:
    [[no_unique_address]] Empty e;
    int value;
};
 
int main() {
    std::cout << "sizeof(Empty): " << sizeof(Empty) << "\n";
    std::cout << "sizeof(WithEBO): " << sizeof(WithEBO) << "\n";
    std::cout << "sizeof(NoEBO): " << sizeof(NoEBO) << "\n";
    std::cout << "sizeof(Modern): " << sizeof(Modern) << "\n";
 
    return 0;
}
wiki/cpp-empty-base-optimization.md · Last modified: by 127.0.0.1