[英]g++ and clang++ different behaviour with stream input and unsigned integer
I came across a difference in behavior, between gcc (4.9.2) and clang (3.5.0), which surprised me. 我发现gcc(4.9.2)和clang(3.5.0)之间的行为有所不同,令我感到惊讶。
When I try to feed an unsigned int
from an std::istringstream
initialized with a negative value ("-15", in the example) I get 当我尝试从使用
std::istringstream
初始化的std::istringstream
提供unsigned int
(在示例中为“-15”),我得到
fail()
bit raised) with clang++ fail()
位) signed(-15)
with gcc++ signed(-15)
进行初始化 I prepared the trivial following example program. 我准备了以下示例程序。
#include <sstream>
#include <iostream>
int main ()
{
std::istringstream iss("-15");
unsigned int ui;
iss >> ui;
std::cout << "ui[" << ui << "] signed(ui)[" << signed(ui)
<< "] flags[" << iss.fail() << iss.good() << iss.bad()
<< iss.eof() << "]\n";
return 0;
}
With clang++, I obtain the following output 使用clang ++,我获得以下输出
ui[0] signed(ui)[0] flags[1001]
With g++, I obtain the following output 使用g ++,我获得以下输出
ui[4294967281] signed(ui)[-15] flags[0001]
I have two questions. 我有两个问题。
The first is obvious: who's right? 首先是显而易见的:谁是对的? clang++, g++ or is an undefined behaviour?
clang ++,g ++还是一个未定义的行为?
The second is: how can I force the gcc++ to behave like the clang++, giving an error when extracting an unsigned value from a string beginning with a minus? 第二个是:我如何强制gcc ++的行为类似于clang ++,从一个以减号开头的字符串中提取无符号值时会出错?
Thanks and sorry for my bad english. 谢谢,抱歉我的英语不好。
EDIT 2016.04.03 编辑2016.04.03
I realized that this isn't a difference between g++ and clang++, but a difference between libstd++ and libc++. 我意识到这不是g ++和clang ++之间的区别,而是libstd ++和libc ++之间的区别。
Compiling and linking with clang++ and libstd++, I obtain the same output I get with g++. 使用clang ++和libstd ++编译和链接,我获得了与g ++相同的输出。
Sorry. 抱歉。
This has been discussed before here: Negative numeric string (eg "-10") to unsigned short 这在前面已经讨论过: 负数字串(例如“-10”)到无符号短路
The answer is that according to the C++ standard 22.4.2.1.2p3, the conversion is required to fail and the value stores should be: 答案是根据C ++标准22.4.2.1.2p3,转换需要失败,值存储应该是:
the most negative representable value or zero for an unsigned integer type , if the field represents a value too large negative to be represented in val.
对于无符号整数类型 ,最负的可表示值或零 ,如果该字段表示的值太大而无法在val中表示。 ios_base::failbit is assigned to err.
ios_base :: failbit被分配给err。
Therefore, clang++ is the correct behavior. 因此,clang ++是正确的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.