c++ - 为什么这个派生类不是标准布局类?

标签 c++ c++14 language-lawyer c++17

为什么 bar 不是 C++17 下的标准布局类型?

#include <type_traits>

class foo {
    int x;
};

static_assert(std::is_standard_layout<foo>::value);

class bar : public foo {
    float y;
};

static_assert(std::is_standard_layout<bar>::value); // "static assertion failed"

基于 CPP Reference descriptiona very similar question我明白为什么这不是 C++14 之前的标准布局类型,但我无法连接 CPP reference's description item那,通过排除其他一切,应该是一个适用于这里的:“没有一个基类子对象具有相同的类型 对于非 union 类型,作为第一个非静态数据成员(参见空基优化),并且递归地,如果它具有非 union 类类型,则作为该数据成员的第一个非静态数据成员,或者所有非静态该数据成员的数据成员,如果它具有 union 类型,或者该数据成员的元素,如果它具有数组类型,等等。”

最佳答案

bar 在您引用的那个之前不满足要求(来自 cppreference.com page on standard layout classes ):

Requirements:

  • [...]

  • Has all non-static data members and bit-fields declared in the same class (either all in the derived or all in some base)

  • [...]

bar 有一个直接的非静态数据成员 float y; 和一个继承自 的非静态数据成员 int x; >foo.


自 C++14 以来,此特定要求的措辞(在大多数情况下?)在功能上等同于之前的措辞,并且在您链接的问题的答案中也提到了这一点。

更改它只是因为措辞上可能存在误解,请参阅 CWG issue 1813和位字段被添加到其中,因为它们可能没有包含在术语成员中,参见CWG issue 1881 .

关于c++ - 为什么这个派生类不是标准布局类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696535/

相关文章:

c++ - QLocale - 验证价格

c++ - 窗口不断获取 WM_WINDOWPOSCHANGING

c++ - 缩写函数模板与带有转发引用参数的函数模板

c++ - 可以解释一下此输出的逻辑吗?

c++ - 为什么 C++11 或 C++14 中没有位置迭代器?

c++ - 从函数返回的引用的生命周期

C++ 重构预编译头文件

c++ - msvcr100d.dll 中未处理的异常

c++ - 有没有办法为用户定义的类型强制/建议 "statement has no effect"警告

c++ - 是否正在使用 placement-new,复制存储然后访问值未定义行为?