attributesc++20datamember

Why C++ non-static data members require unique addresses?


Recently C++ has added the feature [[no_unique_address]] for empty data types such as struct empty {};.

How do empty data memberes benefit from having a unique address?

Why wouldn't the standard make all empty data members address-less?

Why C++ non-static data members require unique addresses?


Solution

  • Because (among other things), that's how C does it. If C++ was to be able to be layout-compatible with C, then an empty NSDM of a C++ struct would have to take up the same space as an equivalent C declaration.

    Empty base class optimization was able to be added to C++ because base classes aren't C language features, so there was never any question about compatibility with C. If you want to allow empty member optimization, you have to have the C++ programmer be explicit about whether they want to make the optimization available (and therefore, the type isn't directly compatible to a C type). You can't just spring it on them.