gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:57:14 25 4
gpt4 key购买 nike

我正在尝试转换 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com