假设在C++03中给定一个POD-struct,或者在C++11中给定一个标准布局类型,并且所有成员都具有基本对齐要求,那么每个成员是否保证根据其对齐要求对齐?
换句话说,对于标准布局类型的所有成员…
struct S { T0 m0; T1 m1; ... TN mn; };
以下表达式是否保证得出true
?
(offsetof(S,m_k) % alignof(decltype(S::m_k))) == 0
根据C++03标准(ISO/IEC 14882:2003(E)),除了第一个成员之外,POD结构体中成员的对齐是不确定的。C++03标准对此不做规定,但应该按照对象类型的对齐方式进行内存分配。结构体成员间可能存在填充,但这取决于实现的对齐要求。在POD结构体中,第一个成员将按照结构体的对齐方式进行对齐。
还需要引用标准的以下部分:
1.8 The C++ object model [intro.object] 1.8/1 The constructs in a C++ program create, destroy, refer to, access, and manipulate objects. An object is a region of storage.
3.9 Types [basic.types] 3.9/5 Object types have alignment requirements (3.9.1, 3.9.2). The alignment of a complete object type is an implementation-defined integer value representing a number of bytes; an object is allocated at an address that meets the alignment requirements of its object type.
3.9.1 Fundamental types [basic.fundamental] 3.9.1/3 For each of the signed integer types, there exists a corresponding (but different) unsigned integer type: "unsigned char", "unsigned short int", "unsigned int", and "unsigned long int," each of which occupies the same amount of storage and has the same alignment requirements (3.9) as the corresponding signed integer type;...
9.2 Class members [class.mem] 9.2/12 Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
9.2/17 A pointer to a POD-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 POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment.]