§12.1/4:及其第一个要点
A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class. A defaulted default constructor for class X is defined as deleted if:
- X is a union-like class that has a variant member with a non-trivial default constructor,
根据这个要点,这个片段不应该编译,因为 struct A
是一个类似 union 的类(它包含一个匿名 union )并且它有一个变体成员,B b;
带有一个非平凡的默认构造函数。但是 code compiles without a problem in vc++, clang++ and g++ .
#include <iostream>
struct B { B(): i(10) {} int i; };
struct A
{
union{ int y = 1; double x; };
int i;
A(int j) : i{j} {};
B b;
A() = default;
};
int main() {
A a;
}
最佳答案
变体成员是
union{ int y = 1; double x; };
而且它们都没有非平凡的构造函数。
这在 §9.5/8 中定义:
9.5 Unions [class.union]
8 A union-like class is a union or a class that has an anonymous union as a direct member. A union-like class X has a set of variant members. If
X
is a union its variant members are the non-static data members; otherwise, its variant members are the non-static data members of all anonymous unions that are members ofX
.
关于c++ - 根据 C++11 标准中的 §12.1/4,代码不应编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093669/