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.
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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?