Boost logo

Boost Users :

Subject: [Boost-users] [optional] Could (& should) optional be more space efficient?
From: David Blaikie (dblaikie_at_[hidden])
Date: 2011-04-11 14:19:06

>From my initial look through boost::optional's implementation, it seems as
though it's doing nothing to optimize its space usage in some trivial cases.

The first one I was surprised by was optional<T&> - still uses sizeof(struct
{ T& t; }) + sizeof(bool) space, rather than simply using a pointer to
represent both the reference and the unspecified state (using null, since a
reference doesn't use that state). Is there a reason for this (perhaps I'm
missing something & a reference is smaller than a pointer in certain

Similarly - would it be worth considering optimizing optional<bool> (though,
as per the documentation, this is perhaps a little "tricky" at best, owing
to the implicit bool of optional itself) to use one byte instead of two?

[long term - I'm wondering if a generic "efficient optionality" could be
implemented by arbitrary types - privately exposing an extra unused state
from their representation for use by optional only. Then, potentially,
making versions of (boost/std)::shared_ptr/unique_ptr that would be
never-null (only constructible via make_shared like machinery) &
optional<shared_non_null_ptr<T>> would then be an explicit representation of
the optional situation, but without any overhead - shared_non_null_ptr<T>
would simply expose its null state only to optional<shared_non_null_ptr<T>>]

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at