[lexical_cast] Strange behaviour

Trying again 'cos I mucked up the code last time! This code #include <iostream> #include <boost/lexical_cast.hpp> int main() { using namespace std; try { unsigned int u=boost::lexical_cast<unsigned int>("-1"); cout << u << '\n'; } catch(const std::exception&) { cout << "Exception" << '\n'; } } produces 4294967295 on MSVC7 & 8 rather than an exception. Is it supposed to do this? Rob.

Hi Rob,
This code
produces
4294967295
on MSVC7 & 8
rather than an exception. Is it supposed to do this?
I'd say yes, since a conversion from int to unsigned int is well defined, so I would expect lexical_cast to work in the same way in this case. Consider paragraph 2 of section 4.7 of the 2003 edition of the C++ standard: "If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]" Regards, Eugene Wee
participants (2)
-
Eugene Wee
-
Robert Jones