Extending the empty base class optimisation (EBO) to members

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.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

3 Responses to Extending the empty base class optimisation (EBO) to members

  1. gold account says:

    Size of an object is nothing but the cumulative size of it’s members. And NO, no class can have a zero size, even an empty class will have a size of 1 byte.

    • robdesbois says:

      Sorry but that’s not correct: although an empty class instance cannot have zero size, as per the quote from the 2011 standard (§1.8/5) a base class subobject may have zero size. The 2003 standard has the same spec with same section number. I don’t have the 1998 spec to hand. (Note that for obvious reasons I have removed the spam URL from your comment and assumed that you really did wish to discuss the post.)

  2. Yay, standard citations! Pleasing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s