c++ - 空基类优化现在是强制优化吗(至少对于标准布局类)?

标签 c++ c++11 language-lawyer

根据 C++11 9.1/7 (draft n3376)standard-layout 类是: p>

  • 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 (Clause11) 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/19 声明:

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]

这似乎暗示 空基类优化 现在是强制优化,至少对于 standard-layout 类是这样。我的观点是,如果不强制要求空基优化,那么 standard-layout 类的布局将不是标准的,而是取决于实现是否实现了所述优化。我的推理是否正确,还是我遗漏了什么?

最佳答案

是的,你说得对,“重新审视 POD”提案中指出了这一点:http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2007/n2342.htm#ABI

Embarcadero 编译器文档也说明了这一点:http://docwiki.embarcadero.com/RADStudio/en/Is_standard_layout

另一个关键点是[class.mem]/16

Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).

请注意,只有数据成员会影响布局兼容性,而不是基类,因此这两个标准布局类是布局兼容的:

struct empty { };
struct stdlayout1 : empty { int i; };

struct stdlayout2 { int j; };

关于c++ - 空基类优化现在是强制优化吗(至少对于标准布局类)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10788823/

相关文章:

c++ - 如何修复无限 while 循环?

c++ - 为什么具有非常量复制构造函数的类不被视为可复制构造?

c++ - 使用 C++ 模板魔法进行通用和存在量化

c++ - 冲突的模板定义和 ODR

c++ - 测地球的算法

c++ - 两个 vector 的可迭代并集

c++ - 使用用户定义的比较类对 std::pair 的 std::vector 进行排序

c++ - 未评估上下文中的 "Cannot call member function ... without object"- GCC 错误?

c++ - 在初始化内存上使用 placement new 是否合法?

c++ - 当编译时已知引用占用非聚合结构中的空间时,是否错过了优化?