本文介绍了g ++ 49和g ++ 5在初始化列表中变窄时的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

请考虑此代码:

  #include< iostream& 

int main()
{
int i {10.1}; // narrowing,should not compile
std :: cout<< i<< std :: endl;
}

根据C ++ 11标准,它不应该编译)



现在,使用 g ++ 4.9.2 -std = c ++ 11编译只发出警告

 警告:将'1.01e + 1'的转换从'double' }删除 -std = c ++ 11    / code>标志导致关于括号init的警告,但没有任何缩小:

 警告:扩展初始化列表仅适用于-std = c ++ 11或-std = gnu ++ 11 

只要您使用 g ++ 5 -std = c ++ 11 编译,就可以使用g ++ 5 不编译。但是,如果省略 -std = c ++ 11 ,则甚至 g ++ 5

 警告:扩展初始化器列表只能使用-std = c ++ 11或-std = gnu ++ 11 

上述行为似乎错误, g ++ 4.9 不应该编译代码,如果你忘记指定 g ++ 5 -std = c ++ 11 。这是一个已知的问题吗?

解决方案

标准从来没有说过不应该编译。



您可以使gcc停止所有诊断的编译,方法是使用开关 -Werror 。它可以缩小到特定的警告,例如。 -Werror = narrowing



如果您正在使用GNU ++或任何默认模式



参考:N3936 [intro.compliance] / 2

[defns.diagnostic]


$ b b

消息属于实现的输出消息的实现定义的子集 p>

请注意,从第一个要点来看,不要求消息的数量或内容对应于违规的数量或内容。



标准完全由编译器决定如何组织其错误和/或警告,条件是对于某些违规,它不能默默地忽略它。


Consider this code:

#include <iostream>

int main()
{
    int i{10.1}; // narrowing, should not compile
    std::cout << i << std::endl;
}

According to the C++11 standard, it should not compile (narrowing in brace initialization is forbidden.)

Now, compiling with g++4.9.2 -std=c++11 only emits a warning

warning: narrowing conversion of '1.01e+1' from 'double' to 'int' inside { } [-Wnarrowing]

Removing the -std=c++11 flag results in a warning regarding the brace init, but not any narrowing:

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11

On the other hand, g++5 doesn't compile it, provided you compile with g++5 -std=c++11. However, if -std=c++11 is omitted, then even g++5 happily compiles it, giving just a warning related to the brace init, not to the narrowing:

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11

The above behaviour seems buggy, g++4.9 should not compile the code, and it is more than weird that g++5 compiles it if you forget to specify -std=c++11. Is this a known problem?

解决方案

The standard never says anything "should not compile" . Certain ill-formed programs must emit a diagnostic and issuing a warning satisfies that.

You can cause gcc to stop compilation on all diagnostics by using the switch -Werror. It can be narrowed to specific warnings, e.g. -Werror=narrowing.

If you are compiling in GNU++ or whatever the default mode is instead of C++11 then the compiler can do whatever it likes, including accepting narrowing conversions without complaint.

Reference: N3936 [intro.compliance]/2

[defns.diagnostic]

Note also from the first bullet point that it is not required that the number or content of messages corresponds to the number or content of the violations.

The standard leaves it completely up to the compiler to decide how to organize its errors and/or warnings, with the proviso that for certain violations it can't silently ignore it.

这篇关于g ++ 49和g ++ 5在初始化列表中变窄时的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:08