Archive for September, 2012

Extending the empty base class optimisation (EBO) to members

September 10, 2012 3 comments

The empty base class optimisation or EBO is a space-saving technique that is employed by many popular C++ compilers. Simply put by the standard (§1.8/5 in all versions):

…a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size.

This technique is employed in particular by some standard library implementation where a container template class’ constructor takes a (templated) allocator instance. Even if an allocator object is empty, to accept and store it as a distinct member sub-object requires that it occupy real space within the container class instance; this will likely be 1 byte (the minimum non-zero size) plus whatever padding is required for your platform’s alignment (likely a further 3 or 7 bytes for 32-bit or 64-bit respectively). By instead making the allocator type a base class of the container, this space is no longer required.

I recently found an alternative approach described by Nathan Myers in 1997, in which he wraps some other member object in a special-purpose struct, and then makes the empty type a base of that, thus still employing EBO. It’s a nifty little technique that, although rarely likely to be useful, will be of immense help should I ever have an issue with memory footprint of such a type.

All the detail can be read on Nathan’s website here: The “Empty Member” C++ Optimization.

Categories: Uncategorized Tags:

Get every new post delivered to your Inbox.