c++ - 标准布局 c++

标签 c++ c++11 standard-layout

我正在浏览 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.

如果没有此限制,以下类型(Type1Type2)将不可能是布局兼容的(尽管它们将是标准布局类)。

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/

相关文章:

c++ - STL 容器有任何标准布局保证吗?

c++ - 求一个点到椭圆的距离,无论是在椭圆内还是在椭圆外

c++ - 如何将 const std::shared_ptr 插入 std::map

c++ - 访问标准布局类的私有(private)非静态第一个数据成员是否合法?

c++ - 在 C++ 中使用不同的分配器复制对象

c++ - 公共(public)基类打破了元组的空基类优化

c++ - 为什么C++1 1's POD "标准布局“定义是这样的?

c++ - 在 C++11 中处理可变参数模板

c++ - 如何从 priority_queue 中拉出 unique_ptr 并维护所有权语义

c++ - 我可以在 1 行中使用非默认数据类型作为函数的参数吗?