Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

According to §12.1/4 in the C++11 Standard, the code shouldn't compile

§12.1/4: and its first bullet point

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,

According to this bullet point this snippet should not compile, as struct A is a union-like class (it contains an anonymous union) and it has a variant member, B b; with a non-trivial default constructor. But the 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;
}
like image 677
Belloc Avatar asked Jan 13 '14 14:01

Belloc


1 Answers

The variant members are

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

and none of them has a non-trivial constructor.

This is defined in §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 of X.

like image 105
Daniel Frey Avatar answered Oct 08 '22 21:10

Daniel Frey