为什么std :: stoul会转换负数?
如 http://ideone.com/RdINqa 中所示, std :: stoul
不会为负数抛出 std :: out_of_range
,而是将它们包装起来。为什么是这样?好像-4超出了 unsigned long
类型的范围,因此它应该抛出。
As shown in http://ideone.com/RdINqa, std::stoul
does not throw a std::out_of_range
for negative numbers, but wraps them around. Why is this? Seems like -4 is out of the range of the type unsigned long
so it should throw.
21.5 数值转换
无符号长stoul(const string& str,size_t * idx = 0,int base =
10);
效果: ... call [s] strtoul(str.c_str(),ptr,base)
...返回转换后的结果(如果有)。
Effects: ...call[s] strtoul(str.c_str(), ptr, base)
... returns the converted result, if any.
抛出: ... out_of_range
如果转换后的值超出返回类型可表示值的范围。
Throws: ...out_of_range
if the converted value is outside the range of representable values for the return type.
转换后的价值是 strtoul
返回的值。当然,它的类型为 unsigned long
,因此对于 stoul的返回类型,不能超出可表示值的范围
,它也是 unsigned long
。
"Converted value" here is the value returned by strtoul
. Which, of course, is of type unsigned long
and so can't be outside of the range of representable values for the return type of stoul
, which is also unsigned long
.
据我所知,只有 stoi
可以抛出 out_of_range
,因为它返回 int
但使用 strtol
会返回 long
。
As far as I can tell, only stoi
can throw out_of_range
, because it returns int
but uses strtol
which returns long
.
此外,采用C标准指定 strtoul
,则需要接受字符串-4
并返回等于-(无符号长)4 。我不知道为什么要这样指定。
Further, the way C standard specifies strtoul
, it is required to accept the string "-4"
and return a value equal to -(unsigned long)4
. Why it's specified this way, I don't know.