The following code throws an exception when it is run under Visual Studio 2013 but not gcc 4.9.2.
The error reported is:
'exception: stol argument out of range'
stol returns a long so the size of temp should be big enough to hold the returned value.
Can anyone explain the behaviour. Is this possibly a compiler bug?
#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;
}
Under Windows the type
longis always 32-bits. Sincelongis a signed integer type this means that the range oflongis between -2147483648 and 2147483647 inclusive. On Linux the size oflongdepends on whether you're compiling for 32-bits or 64-bits.Since
std:stolconverts a string tolongthe result must fit into along. If it doesn't then the function throwsstd::out_of_range. To resolve this problem you can usestd::stollwhich returns along long, which is guaranteed to be at least 64-bits and so won't ever throw an exception when converting"4294967295". You can also usestd::stoul, which converts to aunsigned long, which is is guaranteed to have a range of at least 0 to 4294967295.(Note that this is not strictly a Visual C++ versus GCC thing. When targeting Windows, GCC also always uses a 32-bit
long.)