对象的大小是否受访问说明符类型和继承类型影响?
在回答其中一个问题时,有一个讨论线程 低于我的答案。这表明,根据访问说明符(或者可能是继承类型)private/protected/public
,class
对象的 sizeof
可能会有所不同!
从他们简短的讨论中我仍然不明白,这怎么可能?
While answering one of the question, there was a discussion thread below my answer. Which suggests that depending on the access specifier (or may be the type of inheritance) private/protected/public
the sizeof
the class
object may vary!
I still don't understand from their brief discussion, how is that possible ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意下面 C++11 的新语言
在 C++03 中,有一种语言可以实现这一点,9.2 [class.mem]/12(重点是我的):
因此给出这样的定义:
在具有 32 位 (
int
) 对齐的系统上,编译器不允许将c
重新排序到b
之前,强制在a
和b
之间以及c
之后插入额外的填充填充到对象的末尾(使得sizeof( Foo) == 12
)。但是,为此:a
和 (b
和c
) 由访问说明符分隔,因此编译器可以自由地执行此类重新排序,使sizeof(Foo) == 8
。在 C++11 中,语言略有变化。 N3485 9.2 [class.mem]/13 说(强调我的):
这意味着在C++11中,在上面的例子中(由3个public分隔),编译器仍然不允许执行重新排序。它必须类似于
,它将
a
、b
和c
置于不同的访问控制中。请注意,根据 C++11 规则,给出如下定义:
编译器必须将
d
放在b
之后,即使它们由访问说明符分隔。(也就是说,我不知道有任何实现实际上利用了任一标准提供的自由度)
Note new language for C++11 below
In C++03, there is language that makes this possible, 9.2 [class.mem]/12 (emphasis mine):
So given this definition:
on a system with 32 bit (
int
) alignment, the compiler is not allowed to reorderc
to come beforeb
, forcing the insertion of additional padding padding in betweena
andb
, and afterc
to the end of the object (makingsizeof(Foo) == 12
). However, for this:a
and (b
andc
) are separated by an access specifier, so the compiler is free to perform such reordering, makingsizeof(Foo) == 8
.In C++11, the language changes slightly. N3485 9.2 [class.mem]/13 says (emphasis mine):
This means that in C++11, in the above example (separated by 3 publics), the compiler is still not allowed to perform the reordering. It would have to be something like
, which places
a
,b
, andc
with different access control.Note that under the C++11 rules, given a definition like:
the compiler must put
d
afterb
, even though they are separated by access specifiers.(That said, I'm not aware of any implementation that actually takes advantage of the latitude offered by either standard)