GCC和-Wconversion [英] GCC and -Wconversion

查看:83
本文介绍了GCC和-Wconversion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们编译以下程序:

int main()
{
    uint16_t data = 0;
    data |= uint16_t(std::round(3.14f));
    return 0;
}

g ++ -Wconversion prog.cpp

我们会得到警告:从'int'转换为'uint16_t {aka short unsigned int}'可能会改变其值,但我在这里看不到隐式转换.

We'll get warning: conversion to ‘uint16_t {aka short unsigned int}’ from ‘int’ may alter its value, but I can't see implicit conversions here.

此类警告应通过显式强制转换忽略,例如:

This kind of warnings should be muted by explicit casts, for example:

double d = 3.14;
float foo1 = d; // Warning
float foo2 = float(d); // No warning
float foo2 = static_cast<float>(d); // No warning

GCC在这里还是一个错误?

Is GCC right here or it's a bug?

请注意,我的代码段很小.例如,在以下情况下警告会消失:

Note that my snippet is minimal. For example, warning disappears in following cases:

  • 3.14 删除 f 后缀,即使其成为 double
  • 使用分配而不是 | =
  • 删除 std :: round
  • 缓存舍入结果: const auto r = uint16_t(std :: round(3.14f)); ,然后将其或分配给 data .
  • remove the f suffix from 3.14, i.e. make it double
  • use assignment instead of |=
  • remove std::round
  • cache rounding result: const auto r = uint16_t(std::round(3.14f));, then or-assign it to data.

推荐答案

警告是虚假的.

根据 [over.built]/22 :

对于每个三元组( L,VQ,R ),其中 L 是整数类型, VQ 是volatile或为空,并且 R 是一种提升的整数类型,存在形式为...

For every triple (L, VQ, R), where L is an integral type, VQ is either volatile or empty, and R is a promoted integral type, there exist candidate operator functions of the form ...

VQ L&   operator|=(VQ L&, R);

因此我们得到一个内置的 unsigned short运算符| =(unsigned short& ;, unsigned int);

So we get a built-in unsigned short operator |=(unsigned short&, unsigned int);

给定表达式中没有隐式转换

There are no implicit conversions in the given expression

uint16_t data = 0;
data |= uint16_t(std::round(3.14f));

这篇关于GCC和-Wconversion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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