Should I use list initialization in the list of constructor initializers?

In GotW # 6b, part 2, we will find the code

class polygon { public: polygon() : area{-1} {} //.... double area; }; 

Why should we use list initialization for basic types instead of the commonly used area(-1) ? Are there any advantages / situations in which they behave differently?

+4
source share
2 answers

Why should we use list initialization for the base types instead of the scope used (-1)?

First of all, I think there is a message that C ++ 11 uniform initialization should be used whenever it can be used. In this case, it is mainly a matter of style and taste.

It will be hard to say at this time whether the style and taste promoted by the author will become the de facto standard. We all know that uniform initialization is not such a uniform. On the other hand, in most situations, the advantages of using it as the default coding style are attractive - syntactic homogeneity, as well as the fact that problems like Most Vexing Parse disappear.

Moreover, when the list of initializers contains only one element, the initialized object is initialized from this element (ยง 8.5.4 / 3). This makes initialization in your example equivalent to regular direct initialization (except that narrowing conversions is unacceptable).

In other words, area{-1} and area(-1) in your example are both direct initializations and equivalent. Choosing one over the other is only a matter of style.

Are there any advantages / situations in which they behave differently?

As mentioned above, one situation in which they behave differently is determined by initialization, which involves narrowing conversions. For example, if it is allowed:

 int x{42}; 

Is not:

 int y{3.14}; // ERROR! Narrowing conversion 
+6
source

This would not affect the scalars, but the author probably corresponded to the new syntax. For example, before C ++ 11 you could not initialize arrays through the list of initializers, but this can be easily done through aggregate initialization:

 struct A { A() : data{1, 2, 3} // this wouldn't work as 'data(1, 2, 3)' {} int data[3]; }; 

Similarly, you would do the same for vectors.

+3
source

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


All Articles