Re: Empty structures have sizeof(1) in C++ now ?
- In reply to: David Chisnall : "Re: Empty structures have sizeof(1) in C++ now ?"
- Go to: [ bottom of page ] [ top of archives ] [ this month ]
Date: Fri, 21 Feb 2025 18:39:46 UTC
On 2/20/25 12:03, David Chisnall wrote: > No, that’s always been the case in C++. It comes from the rule that two allocations must have unique addresses. If a structure could have size zero, an array of these structures would have size zero and the two elements in the array would have the same address. Similarly, two struct fields could have the same address, which breaks other bits of the language (pointers to members would compare equal when they should not). > > C++20 introduced the no_unique_address attribute. This allows you to embed a struct in another and, if the child struct has no fields, then its address is not required to be unique and you are explicitly saying that you won’t do any of the things where this would be a problem. > > This lets you do things like: > > ```c++ > template<typename Embedded=void> > struct SomeStructThatMayContainAnother > { > // Normal fields go here > > [[no_unique_address]] > std::conditional_t<std::is_same_v<Embedded, void>, struct {}, Embedded> embeddedStruct; > > // More fields maybe here > }; > ``` > > In this case, `embeddedStruct` will not add any space to the parent struct if the template parameter is `void`. There's also "EBO" (empty base optimization). https://en.cppreference.com/w/cpp/language/ebo Empty base classes aren't subject to the requirement that objexts should have an unique address. A+ Paul