std::stoi, std::setbase, and an std::out_of_range error

std::stoi, std::setbase, and an std::out_of_range error

本文关键字:std of error range and stoi setbase an out      更新时间:2023-10-16

使用std::setbase格式化一个数字,将数值最小值int传递给std::stoi会抛出std::out_of_range异常,但我不明白为什么。如果有人能帮助我更好地理解异常背后的原因,我将不胜感激

代码段:

#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
template <typename T>
std::string toString(const T x, const int base)
{
    std::stringstream ss;
    ss << std::setbase(base) << x;
    return ss.str();
}   
int main(void)
{
    const int x = std::numeric_limits<int>::min();
    std::size_t index = 0;
    const auto base = 16;
    const auto s = toString(x, base);
    std::cout << "base-10: " << x << std::endl
              << "base-" << base << ": " << s << std::endl;
    std::cout << std::stoi(s, &index, base) << std::endl;
    return 0; 
}   

输出:

base-10: -2147483648 
base-16: 80000000 
terminate called after throwing an instance of 'std::out_of_range'
  what():  stoi 
Aborted (core dumped)

std::stoX函数不会为没有前缀为-的字符串返回负值。0x80000000是231,它不能用有符号的32位整数表示,因此存在溢出,因此引发异常。