When should you use single initialization?

In C++11 you can initialize a struct using standard initialization, as shown below:

 struct BasicStruct { BasicStruct (int x, double y) : x_{x}, y_{y} {} private: int x_; double y_; }; BasicStruct var1{5, 3.2}; 

Questions:

  • When should I use this syntax BasicStruct var1{5, 3.2} instead of calling the constructor of type BasicStruct var1(5, 3.2) ?

  • When do I need to initialize an attribute of type x_{x} instead of the old method x_(x) ?

+6
source share
1 answer

Use an initialization list when the list is shared, and you can replace another container, such as an array, aggregate, or vector , without changing its value.

 // "triplet" may be a struct, an array, or a std::vector, // but it has at least single-precision floating-point values. triplet dimensions { 5, 1.2f, static_cast< float >( M_PI ) }; 

If you create a specific class with arguments for a particular constructor, old-fashioned parens are more suitable.

One unique feature of initialization using the bit-init list is that it does not allow you to narrow down conversions that can lead to loss of numeric data, such as the fractional part of a floating-point number or high-order bits of long . This helps to flag (or prevent) errors that occur as a result of replacement, for example, a narrower array type during code refactoring.

Similarly, another case where x{ y } is appropriate is to perform a numerical conversion that you do not want to lose. x( y ) will try very hard to do the conversion, even resorting to reinterpret_cast , and should usually be avoided.

The terminology "uniform initialization" is a bit optimistic, and it does not appear in the standard. This is not suitable for all cases. Brackets usually indicate lists, so they are correctly called list initialization. And just then it should be used.

+4
source

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


All Articles