为什么列表初始化(使用花括号)比其他方法更好?

MyClass a1 {a};     // clearer and less error-prone than the other three
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);

为什么?

推荐答案

基本上是从 Bjarne Stroustrup 的 The C++ Programming Language 4th Edition"中复制和粘贴:

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

列表初始化不允许缩小 (§iso.8.5.4).那就是:

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • 一个整数不能转换为另一个不能保存其值的整数.例如,字符允许转换为 int,但不允许转换为 char.
  • 无法将浮点值转换为另一种无法保存其的浮点类型价值.例如,允许双精度浮点数,但不允许双精度浮点数.
  • 浮点值不能转换为整数类型.
  • 整数值不能转换为浮点类型.

例子:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}


only = 优先于 {} 的情况是使用 auto 关键字来获取由初始化程序确定的类型.


The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

例子:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int


结论

除非您有充分的理由不这样做,否则更喜欢 {} 初始化.

相关文章