std::stoul not throwing std::out_of_range

std::stoul not throwing std::out_of_range

本文关键字:std range of throwing stoul not out      更新时间:2023-10-16

请考虑以下代码:

#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;
}

这段代码应该从strerror打印一些"超出范围",然后根据文档抛出out_of_range异常。它永远不应该到达最后一条线。

在实践中,它不会抛出第二个 stoul 语句。我尝试过 GCC 4.8.5 和 MinGW 8.2.0,两者都未能抛出out_of_range异常,并且仅在最后一个 stoul 语句上提供了invalid_argument。

这是一个应该报告的错误,还是我遗漏了什么,这是预期的行为?

std::stoul的默认

基数为 10。
stoul读取 0x无效,因此忽略字符串的其余部分并返回数值 0

使用与 strtoul 中类似的语法:

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

或者自动扣除数字基数:

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

以上两个版本都会抛出。在线查看!