当前位置 : 主页 > 编程语言 > c++ >

c – 为什么gcc警告只为统一初始化缩小转换?

来源:互联网 收集:自由互联 发布时间:2021-06-23
我试图将长类型变量转换为具有 uniform initialization 的int类型变量,没有它.但是我只能通过统一初始化获得编译器警告.这是为什么?为什么gcc不警告两种情况?我也尝试过clang并得到了类
我试图将长类型变量转换为具有 uniform initialization的int类型变量,没有它.但是我只能通过统一初始化获得编译器警告.这是为什么?为什么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

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

网友评论