In the post about [[no_unique_address]] attribute
we’ve looked at how this handy attribute can help us avoid wasting memory on stateless policies. But what if we have to use older than C++20 version of C++? Well, it can certainly be done using a combination of template metaprogramming and inheritance, but it’s not for the faint of heart and this extra complexity may be somewhat hard to justify.
Fortunately, all of this magic is already done in std::tuple, so instead of
we can bundle state into a tuple
and get the following difference
Note, that this trick doesn’t work with std::pair
Note, that because of alignment, in addition to 1 byte taken by Destroyer, 3 padding bytes are also wasted. These 4 bytes quickly add up and can have significant performance impact because of inefficient use of cache.
As always, you can explore this use-case in compiler explorer.
great trick! thanks for posting.
so is it because tuple is impl w/ inheritance and the compiler is using empty base class optimization?