我正在浏览 C++ POD, Trivial and Standard Layout classes 上的精彩文章 我还没有清楚了解标准布局的一个属性如下:-
A standard layout has no base classes of the same type as the first
non-static data member
因此以下将不是标准布局,因为它的第一个成员与基类相同
struct NonStandardLayout3 : StandardLayout1 {
StandardLayout1 x; // first member cannot be of the same type as base
};
但是在性能方面和属性方面,上述结构有何不同
struct StandardLayout5 : StandardLayout1 {
int x;
StandardLayout1 y; // can have members of base type if they're not the first
};
这是对上面那个的更正。
最佳答案
原因是标准布局类型有效地要求“空基类优化”,其中没有数据成员的基类不占用空间,并且与派生类的第一个数据成员(如果有)具有相同的地址。
但是,当基类与第一个数据成员具有相同类型时尝试这样做违反了 C++ 内存模型,该模型要求相同类型的不同对象必须具有不同的地址。
来自 ISO/IEC 14882:2011 1.8 [intro.object]/6:
Two objects that are not bit-fields may have the same address if one is a subobject of the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they shall have distinct addresses
有效地强制空基类,9.2 [class.mem]/20:
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.
如果没有此限制,以下类型(Type1
和 Type2
)将不可能是布局兼容的(尽管它们将是标准布局类)。
struct S1 {};
struct S2 {};
struct Type1 : S1 {
S1 s;
int k;
};
struct Type2 : S1 {
S2 s;
int m;
};
关于c++ - 标准布局 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11300439/