How do I write EBO-friendly classes (empty base optimization) for low-latency systems?

In C++, Empty Base Optimization (EBO) allows empty base classes to be optimized away by the compiler to save memory. This can be particularly useful in low-latency systems where every byte counts. In this article, we will explore how to implement EBO-friendly classes in C++ with an example.

EBO, Empty Base Optimization, C++, low-latency systems, memory optimization, C++ classes
Learn how to implement EBO-friendly classes in C++ for low-latency systems, maximizing memory efficiency and performance.

class Base {};

template 
class Derived : public Base {
    T value;
public:
    Derived(T val) : value(val) {}
    T getValue() const { return value; }
};

int main() {
    Derived d(42);
    std::cout << "Value: " << d.getValue() << std::endl;
    return 0;
}
    

In the above example, we define a base class `Base` that is empty. The `Derived` class inherits from `Base` and adds a member variable. Thanks to the EBO, if `Base` is empty, the `Derived` class won't add any extra size beyond its member variable, making it efficient in terms of memory usage.


EBO Empty Base Optimization C++ low-latency systems memory optimization C++ classes