Re: What is the correct behaviour?
James Kanze wrote:
Jonne Lehtinen wrote:
Hello, I just stumbled upon two different behaviours with two
different compilers. Here's a sample code....
std::string a( "-432" );
unsigned long b = 0;
std::stringstream stream;
if( !(stream << a && stream >> b) ) {
// Should fail?
}
On g++ 4.1.2 (20061026 (Debian "prerelease")) and g++ 3.4.2 it
does indeed fail but on my school's modified g++ 4.1 (uses
stlport 5.0.1) and on Visual C++ 2005 it doesn't fail. Which
behaviour is correct?
It's undefined behavior, but from a quality of implementation
point of view
IMHO, this is implementation-defined behavior.
In 4.7(Integral conversions), the standard says:
If the destination type is signed, the value is unchanged if it
can be represented in the destination type (and bit-field width);
otherwise, the value is implementation-defined.
The istream's extractors uses num_get, which handling
numeric formatting and conversion.
, I would expect failure. You have the value -432,
which isn't representable in an unsigned long.
Indeed the conversion should fail in my mind.
I test the above code using Boost::lexical_cast, it does
report the fail by throwing bad_lexical_cast exception:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
try {
std::string str("-232");
unsigned long i = lexical_cast<unsigned long>(str);
}
catch(bad_lexical_cast& e) {
std::cout << e.what() << std::endl;;
}
}
$ ./blc
bad lexical cast: source type value could not be interpreted as target
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]