gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:51:35 27 4
gpt4 key购买 nike

根据 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com