Initialization of a default C ++ 11 class member with a list of initializers simultaneously

Can someone please point me to the corresponding paragraph of the C ++ standard, or maybe give some explanation why my code does not compile if I uncomment the text ({123}) ?

In general, I understand that something is wrong with initializing and initializing a member by default through the list of initializers, but I can not refer to the exact reasons.

 enum class MY: int { A = 1 }; struct abc { int a;/*{123};*/ //compilation failed if uncommented MY m; }; abc a = {1, MY::A}; 

Compiler error, in case of undocumented text:

error: could not convert '{1, A} from the list of & initializers included in the list <brace-gt; > to 'abc

+5
source share
1 answer

The syntax is below:

 abc a = {1, MY::A}; 

- This is list initialization, which can be done differently depending on the type initialization. Without a non-static data initializer ( /*{123};*/ ), your structure is an aggregate, and this case falls under [dcl.init.list] / p3 :

  • Otherwise, if T is an aggregate, aggregate initialization is performed.

However, to be an aggregate type, in C ++ 11 the following conditions must be met:

An aggregate is an array or class (section 9) without constructors provided by the user (12.1), without elements with alignment or equal for non-static data elements (9.2) no private or protected non-static data (section 11), no base classes (section 10) and there are no virtual functions (10.3).

Thus, the use of NSDMI (initialization of non-static data) violates the above set of rules, and as a result, an instance of this type can no longer be initialized with a list.

This rule has changed in C ++ 14, and the current wording reads [dcl.init.aggr] / p1 :

An aggregate is an array or class with

  • (1.1) there are no custom, explicit, or inherited constructors ([class.ctor]),

  • (1.2) there are no private or protected non-static data elements ([class.access]),

  • (1.3) there are no virtual functions, and

  • (1.4) there are no virtual, private, or protected base classes ([class.mi]).

[Note. Aggregated initialization does not allow access to elements or constructors of a protected and private base class. - final note]

+5
source

Source: https://habr.com/ru/post/1271139/


All Articles