简体   繁体   English

std :: stoul没有抛出std :: out_of_range

[英]std::stoul not throwing std::out_of_range

Consider following code: 考虑以下代码:

#include <iostream>
#include <cstring>
#include <cerrno>

int main() {
    unsigned long num = strtoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", NULL, 16);
    std::cout << std::strerror(errno) << "\n";
    unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF");
    std::stoul("hello world");
    return 0;
}

This code is expected to print some "Out of range" from strerror and then to throw out_of_range exception according to documentation . 这段代码预计会从strerror打印一些“超出范围”,然后根据文档抛出out_of_range异常。 It should never reach the last stoul line. 它永远不应该到达最后的灵魂线。

In practice, it does not throw on the second stoul statement. 在实践中,它没有抛出第二个stoul声明。 I have tried GCC 4.8.5 and MinGW 8.2.0, both failed to throw the out_of_range exception and only delivered invalid_argument on the last stoul statement. 我尝试过GCC 4.8.5和MinGW 8.2.0,都没有抛出out_of_range异常,只在最后一个stoul语句中传递了invalid_argument。

Is this a bug that should be reported or am I missing something and this is expected behaviour? 这是一个应该报告的错误,还是我遗漏了一些东西,这是预期的行为?

Default base for std::stoul is 10. std::stoul默认基数是10。
stoul reads 0 , x is invalid so the rest of the string is ignored and numeric value 0 is returned. stoul读取0x无效,因此忽略字符串的其余部分并返回数值0

Use similar syntax as in strtoul : 使用与strtoul类似的语法:

unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 16);

Or with automatic deduction of numeric base: 或者自动扣除数字基数:

unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 0);

Both of the above versions will throw. 以上两个版本都会抛出。 See it online! 在线查看!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM