According to ยง 12.1 / 4 in the C ++ 11 standard, code must not be compiled

ยง12.1 / 4: and its first marker point

The default constructor for class X is the constructor of class X, which can be called without an argument. If there is no constructor declared by the user for class X, a constructor without parameters is implicitly declared as default (8.4). The implicitly declared default constructor is an inline public member of its class. By default, the default constructor for class X is determined to be deleted if:

  • X is a unified class that has a variant element with a non-trivial default constructor,

According to this brand, this fragment should not be compiled, since struct A is a unified class (it contains an anonymous union) and has a variant member B b; with a non-trivial default constructor. But the code compiles without problems 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; } 
+7
c ++ constructor language-lawyer c ++ 11
source share
1 answer

Option Elements

 union{ int y = 1; double x; }; 

and not one of them has a non-trivial constructor.

This is defined in No. 9.5 / 8:

9.5 Unions [class.union]

8 A joint class is a union or class that has an anonymous union as a direct member. The combined class X has many options. If X is a union, its members are non-static data members; otherwise, its members are non-static data members of all anonymous associations that are members of X

+13
source share

All Articles