c++ - 为什么 gcc 仅针对统一初始化警告缩小转换?

标签 c++ c++11 language-lawyer compiler-warnings uniform-initialization

我正在尝试转换 long将变量输入到 int类型变量 uniform initialization 没有它。但是我只有在统一初始化时才会收到编译器警告。这是为什么?为什么不gcc在这两种情况下发出警告?我试过 clang也得到了类似的结果。

这是代码

#include <iostream>

int main() {
    long l = 1;
    int i1 = l;
    int i2 = { l };

    std::cout << i1 << std::endl;
    std::cout << i2 << std::endl;

    return 0;
}

我收到的唯一警告
$ g++ -Wall -Wextra 1.cpp
1.cpp: In function ‘int main()’:
1.cpp:6:16: warning: narrowing conversion of ‘l’ from ‘long int’ to ‘int’ inside { } [-Wnarrowing]
   int i2 = { l };

最佳答案

因为标准说,narrowing conversions limit仅指定用于列表初始化 (C++11 起)。

list-initialization limits the allowed implicit conversions by prohibiting the following:

  • conversion from a floating-point type to an integer type
  • conversion from a long double to double or to float and conversion from double to float, except where the source is a constant expression and overflow does not occur
  • conversion from an integer type to a floating-point type, except where the source is a constant expression whose value can be stored exactly in the target type
  • conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type


对于其他初始化方法(使用括号或等号),不应用(添加)缩小转换限制规则;因为这可能会破坏很多遗留代码。

关于c++ - 为什么 gcc 仅针对统一初始化警告缩小转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157182/

相关文章:

c++ - 为什么我们不能在模板静态成员初始化中使用auto?

c++ - 这些析构函数调用背后的逻辑是什么

c++ - 无法识别 main() 函数

c++ - unsigned int 是 `simple-type-specifier`

c++ - 在虚拟继承中交换和复制成语的正确方法是什么?

c++ - 容器的无序迭代

c++ - 64 位架构的 iOS JUCE 库问题

c++ - 我可以使用打印到控制台窗口的内容作为输入吗?

c++ - 大数模幂运算

c++ - Lambda 作为模板变量