Boost logo

Boost Users :

Subject: [Boost-users] [lexical_cast] bad_lexical_cast behavior?
From: Hrvoje Prge¹a (hrvoje.prgesa_at_[hidden])
Date: 2008-09-06 11:16:40


 From the documentation:
"If the conversion is unsuccessful, a bad_lexical_cast exception is
thrown. "
"Exception used to indicate runtime lexical_cast failure. "

So the question is when will the conversion fail? Unit tests check for
the cases between [min(), max()], but what about under/overflows (>max,
<min)? Is it unspecified?

It seems it is currently handled a bit inconsistent:

#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <limits.h>
using std::string;
using std::numeric_limits;
using boost::lexical_cast;
string s;

// warning: needs to be a part of a unit test

//#define min max

#define T short
// add a digit!
s = lexical_cast<string, T>(numeric_limits<T>::min()) + "0";
BOOST_CHECK_THROW(lexical_cast<T>(s), boost::exception); // throws
s = lexical_cast<string, T>(numeric_limits<T>::min()) + "5";
BOOST_CHECK_THROW(lexical_cast<T>(s), boost::exception); // throws

#define T boost::int64_t
s = lexical_cast<string, T>(numeric_limits<T>::min()) + "0";
BOOST_CHECK_THROW(lexical_cast<T>(s), boost::exception); // NO throw!!!
s = lexical_cast<string, T>(numeric_limits<T>::min()) + "5";
BOOST_CHECK_THROW(lexical_cast<T>(s), boost::exception); // throws

The behavior is really weird.
The docs don't mention what should happen.
If I use max instead of min every test throws.

Is there something in boost that can convert a *whole* string to it's
integer representation and throw on under/overflows and errors?

-- Hrvoje Prge¹a


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net