Do the C++ standards guarantee that unused private fields will influence sizeof?
c++, language-lawyer, sizeof
Solution
The C++ standard doesn't define a lot about memory layouts. The fundamental rule for this case is item 4 under section `9 Classes`:
4 Complete objects and member subobjects of class type shall have nonzero size. [ Note: Class objects can be assigned, passed as arguments to functions, and returned by functions (except objects of classes for which copying or moving has been restricted; see 12.8). Other plausible operators, such as equality comparison, can be defined by the user; see 13.5. — end note ]
Now there is one more restriction, though: Standard-layout classes. (no static elements, no virtuals, same visibility for all members) Section `9.2 Class members` requires layout compatibility between different classes for standard-layout classes. This prevents elimination of members from such classes.
For non-trivial non-standard-layout classes I see no further restriction in the standard. The exact behavior of sizeof(), reinterpret_cast(), ... are implementation defined (i.e. 5.2.10 "The mapping function is implementation-defined.").
Problem
Consider the following struct: ``` class Foo { int a; }; ``` Testing in g++, I get that `sizeof(Foo) == 4` but is that guaranteed by the standard? Would a compiler be allowed to notice that `a` is an unused private field and remove it from the in-memory representation of the class (leading to a smaller sizeof)? I don't expect any compilers to actually do that kind of optimization but this question popped up in a language lawyering discussion so now I'm curious.