使用 Visual Studio 但不使用 gcc 的'stol'引发的异常
Exception thrown by 'stol' using Visual Studio but not gcc
以下代码在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
,因此结果必须适合stol
0。如果没有,则函数抛出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
(因此远未溢出(。
不是编译器错误,问题是您的假设无效。
该标准允许long
0低至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
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 字符串长度为10或更长的c++stol抛出范围外异常
- 使用 Visual Studio 但不使用 gcc 的'stol'引发的异常