Properly initialising variables in modern C++ (C++11 and above), using () or {}?

前端 未结 7 991

The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do

7条回答
  •  余生分开走
    2020-12-13 18:40

    There is another important difference: The brace initializer requires that the given type can actually hold the given value. In other words, it forbids narrowing of the value, like rounding or truncation.

    int a(2.3); // ok? a will hold the value 2, no error, maybe compiler warning
    uint8_t c(256); // ok? the compiler should warn about something fishy going on
    

    As compared to the brace initialization

    int A{2.3}; // compiler error, because int can NOT hold a floating point value
    double B{2.3}; // ok, double can hold this value
    uint8_t C{256}; // compiler error, because 8bit is not wide enough for this number
    

    Especially in generic programming with templates you should therefore use brace initialization to avoid nasty surprises when the underlying type does something unexpected to your input values.

提交回复
热议问题