使用 Visual Studio 但不使用 gcc 的'stol'引发的异常

Exception thrown by 'stol' using Visual Studio but not gcc

本文关键字:异常 stol gcc Studio Visual 使用      更新时间:2023-10-16

以下代码在Visual Studio 2013而非gcc 4.9.2下运行时引发异常。

报告的错误为:

"异常:stol参数超出范围">

CCD_ 1返回一个CCD_ 2,因此CCD_。

有人能解释这种行为吗。这可能是编译器错误吗?

#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
int main()
{
    const std::string value = "4294967295";   // 0xffffffff
    try
    {
        int64_t temp = std::stol(value);
    }
    catch (std::invalid_argument& ex)
    {
        std::cout << "invalid_argument: " << ex.what() << "n";
    }
    catch (std::exception& ex)
    {
        std::cout << "exception: " << ex.what() << "n";
    }
   return 0;
}

在Windows下,类型long始终为32位。由于long是有符号整数类型,这意味着long的范围在-2147483648和2147483647之间(包括2147483648和214748364(。在Linux上,long的大小取决于您是编译32位还是64位。

由于std:stol将字符串转换为long,因此结果必须适合stol0。如果没有,则函数抛出std::out_of_range。为了解决这个问题,您可以使用std::stoll,它返回一个long long,保证至少为64位,因此在转换"4294967295"时永远不会抛出异常。您也可以使用std::stoul,它可以转换为unsigned long,保证其范围至少为0到4294967295。

(请注意,这并不是严格意义上的Visual C++与GCC的区别。在针对Windows时,GCC也总是使用32位long。(

我的赌注是visual studio上的32位long(最大2^31,因此溢出(和GCC上的64位long(因此远未溢出(。

不是编译器错误,问题是您的假设无效。

该标准允许long0低至2147483647,因此

CCD_ 21返回一个CCD_ 22,因此CCD_。

这根本不是真的。

所以只需使用std::stoul即可。

乍一看,字符串常数肯定超过了long可以假设的最大值,但不是unsigned long可以具有的最大值。。。

来自

http://en.cppreference.com/w/cpp/string/byte/strtol

strtol返回一个long,您需要strtoll来获得一个long-long