C ++标准是否保证未使用的私有字段会影响sizeof? [英] Do the C++ standards guarantee that unused private fields will influence sizeof?
问题描述
请考虑以下结构:
class Foo {
int a;
};
在g ++中进行测试,我得到了 sizeof(Foo)== 4
,但这是标准所保证的吗?允许编译器注意到 a
是未使用的私有字段,并将其从类的内存表示形式中删除(导致sizeof较小)吗?
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.
推荐答案
C ++标准对内存布局没有太多定义.这种情况的基本规则是 9类
:
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类类型的完整对象和成员子对象的大小应为非零.[注意:可以分配类对象,将其作为参数传递给函数,然后由函数返回(限制了复制或移动的类的对象;请参见12.8).用户可以定义其他合理的运算符,例如相等性比较;见13.5.—尾注]
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 ]
现在,还有一个限制:标准布局类.(没有静态元素,没有虚拟元素,所有成员的可见性相同) 9.2类成员
部分要求标准布局类的不同类之间的布局兼容性.这样可以避免从此类中删除成员.
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.
对于非平凡的非标准布局类,我认为标准中没有进一步的限制.sizeof(),reinterpret_cast(),...的确切行为是由实现定义的(即5.2.10映射函数是由实现定义的.").
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.").
这篇关于C ++标准是否保证未使用的私有字段会影响sizeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!