为什么gcc警告仅缩小统一初始化的转换范围? [英] Why gcc warns about narrowing conversion only for uniform initialization?

查看:121
本文介绍了为什么gcc警告仅缩小统一初始化的转换范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用long 类型变量转换为 int 类型变量/en.cppreference.com/w/cpp/language/list_initialization rel = nofollow noreferrer> 统一初始化 ,并且没有它。但是我只有在统一初始化时才收到编译器警告。这是为什么?为什么在两种情况下 gcc 都不发出警告?我也尝试过使用 clang 并获得类似的结果。

I am trying to convert long type variable to int type variable with uniform initialization and without it. But I get compiler warning only with uniform initialization. Why is that? Why does not gcc warn in both cases? I have tried with clang also and got similar results.

这是代码

#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 };


推荐答案

因为标准说,缩小转换限制仅用于列表初始化(自C ++ 11起)。

Because the standard says, narrowing conversions limit is specified only for list initialization (since C++11).


列表初始化限制
允许的隐式转换,禁止以下操作:

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


  • 从浮点类型转换为整数类型

  • 从长整型转换为double或double,然后从double转换为float,除非source是一个常量表达式
    ,不会发生溢出

  • 从整数类型到浮点类型的转换,除非source是一个可以存储值的常量表达式
    完全符合目标类型

  • 从整数或无作用域枚举类型到无法表示的整数类型的转换nt原始的所有值,除非源
    是一个常数表达式,其值可以精确地存储在
    目标类型中

  • 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

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

For the other initialization methods (using parentheses or equal sign), narrowing conversions limit rule is not applied (added); because that might break much legacy code.

这篇关于为什么gcc警告仅缩小统一初始化的转换范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆