Re: [Boost-bugs] [Boost C++ Libraries] #5494: lexical_cast<unsigned int>("-1") fails to throw

Subject: Re: [Boost-bugs] [Boost C++ Libraries] #5494: lexical_cast<unsigned int>("-1") fails to throw
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2011-05-13 07:47:58


#5494: lexical_cast<unsigned int>("-1") fails to throw
-----------------------------------------------------+----------------------
  Reporter: Rupert Kittinger-Sereinig <rks@…> | Owner: apolukhin
      Type: Bugs | Status: assigned
 Milestone: To Be Determined | Component: lexical_cast
   Version: Boost 1.45.0 | Severity: Problem
Resolution: | Keywords: lexical_cast
-----------------------------------------------------+----------------------

Comment (by apolukhin):

 boost::lexical_cast has the behavior of stringstream, which uses num_get
 functions of std::locale to convert numbers. If we look at the
 [22.2.2.1.2] of Programming languages — C++ ( or at [22.2.2.1.2] Working
 Draft, Standard for Programming Language C++) we`ll see, that num_get uses
 the rules of scanf for conversions. And in the C99 standard for %u the
 input value minus sign is optional, so if a negative number is read, no
 errors will arise and the result will be the two's complement.[[BR]]
 I recommend you to use some wrappers, around lexical_cast, like:

 {{{
 #include <boost/lexical_cast.hpp>
 #include <boost/type_traits/is_unsigned.hpp>

 template <bool is_unsigned>
 struct unsigned_checker
 {
     template<typename String_type>
     static inline void do_check(const String_type & str) { }
 };

 template <>
 struct unsigned_checker<true>
 {
     template<typename String_type>
     static inline void do_check(const String_type & str)
     {
         if( str[0] == '-' ) boost::throw_exception(
 boost::bad_lexical_cast() );
     }
 };

 template<typename Target, typename Source>
 inline Target forced_lexical_cast(const Source &arg)
 {
     unsigned_checker< boost::is_unsigned<Target>::value >::do_check(arg);
     return boost::lexical_cast<Target>( arg );
 }
 }}}
 [[BR]]
 Thank you for that bug report! I`ll add your question to the FAQ section
 of lexical_cast documentation.

-- 
Ticket URL: <https://svn.boost.org/trac/boost/ticket/5494#comment:2>
Boost C++ Libraries <http://www.boost.org/>
Boost provides free peer-reviewed portable C++ source libraries.

This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:06 UTC