结构调整的C / C ++ [英] struct alignment C/C++
问题描述
在C / C ++(我假设他们在这方面是相同的),如果我有以下几点:
In c/c++ (I am assuming they are the same in this regard), if I have the following:
struct S {
T a;
.
.
.
} s;
在下面的保证是真的吗?
Is the following guaranteed to be true?
(void*)&s == (void*)&s.a;
或者换句话说,没有任何种类的保证会有没有填充的前的第一个成员?
推荐答案
在C,是的,他们是同一个地址。简单,明了。
In C, yes, they're the same address. Simple, and straightforward.
在C ++中,没有,他们不是同一地址。基类可以(而且我怀疑,千万)所有成员来之前,和虚成员函数通常隐藏数据的struct地方补充。更令人困惑的,C ++编译器还可以随意重新排列成员,除非类是一个标准的布局类型(虽然我不知道任何编译器这样做)
In C++, no, they're not the same address. Base classes can (and I would suspect, do) come before all members, and virtual member functions usually add hidden data to the struct somewhere. Even more confusing, a C++ compiler may also rearrange members at will, unless the class is a standard layout type (though I don't know that any compiler does so)
最后,如果C ++结构组成的标准布局类型的的,不包含任何的基类,也不虚函数,所有成员都具有相同的知名度,以及其他可能的限制我忘了,的然后的它落回到在C的规则,并且需要第一构件是在相同的地址对象本身。
Finally, if the C++ struct is composed of standard layout types, contains no base classes nor virtual functions and all members have the same visibility, and possibly other limitations I forgot, then it falls back on the C rules, and requires the first member to be at the same address as the object itself.
§9.2 / 7
一个标准的布局类是一类:结果
- 有型非标准布局类(或这些类型的数组)或引用,结果没有非静态数据成员
- 有没有虚函数(10.3),没有虚基类(10.1),结果
- 对所有非静态数据成员相同的访问控制(第11条),结果
- 没有非标准布局基类,结果
- 无论是在最派生类,并在与非静态数据成员最多有一个基类没有非静态数据成员,或具有与非静态数据成员,和结果,没有基类
- 具有类型相同的第一个非静态数据成员的无基类
A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
— has no base classes of the same type as the first non-static data member.
§9.2 / 20
一个指针标准布局结构对象,采用reinter pret_cast适当的转换,指向其初始成员(如该成员是一个位域,然后在它所在的单位)和副反之亦然。 [注:因此,有可能是一个标准的布局结构对象内无名填充,但不是在它的开头,如要达到适当的对准。末端注意事项】
A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. —end note ]
这篇关于结构调整的C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!