c++ - 列表初始化(使用花括号)有什么好处?

标签 c++ c++11 syntax initialization list-initialization

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

为什么?

最佳答案

基本上是从 Bjarne Stroustrup 的 “C++ 编程语言第 4 版” 中复制和粘贴:

列表初始化 不允许缩小 (§iso.8.5.4)。即:

  • 一个整数不能转换为另一个不能保存其值的整数。例如,字符 允许转换为 int,但不允许转换为 char。
  • 一个浮点值不能转换成另一个不能容纳它的浮点类型 值(value)。例如允许float to double,但不允许double to float。
  • 浮点值不能转换为整数类型。
  • 整数值不能转换为浮点类型。

例子:

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)

}

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

例子:

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

结论

除非您有充分的理由不这样做,否则优先选择 {} 初始化。

关于c++ - 列表初始化(使用花括号)有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474890/

相关文章:

powershell - 在PowerShell中等号后是否需要使用反引号?

php - do-while 循环的替代语法(使用冒号)

c++ - 有没有办法将标准输出设置为二进制模式?

c++ - 在参数 C++ 中传递多个参数而不使用 va_list

C++:检查对象是否为非空以便使用 cout 索引每个输出

c++ - 无法迭代其元素包含 unique_ptr 的 map

c++11 - 可变参数类型定义,或 "Bimaps done the C++0x way"

python - 对python函数调用中的**参数感到困惑

c++ - 如何从反汇编中判断是否使用了函数的内部版本?

C++如何制作这种构造函数的原型(prototype)?