为什么 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 description和 a 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/