C++ boost::safe_numerics

C++ boost::safe_numerics


The library implements special versions of intunsigned, etc. Named safe<int>safe<unsigned int> etc. These behave exactly like the underlying types except that expressions using these types fulfill the above guarantee. These "safe" types are meant to be "drop-in" replacements for the built-in types of the same name. So things which are legal - such as assignment of a signed to unsigned value - are not trapped at compile time as they are legal C/C++ code. Instead, they are checked at runtime to trap the case where this (legal) operation would lead to an arithmetically incorrect result.

This library currently applies only to built-in integer types. Analogous issues arise for floating point types but they are not currently addressed by this version of the library. User or library defined types such as arbitrary precision integers can also have this problem. Extension of this library to these other types is not currently under development but may be addressed in the future. This is one reason why the library name is "safe numeric" rather than "safe integer" library.


#include <iostream> #include <boost/safe_numerics/safe_integer.hpp> int main(int, const char *[]) { std::cout << "example 1:"; std::cout << "undetected erroneous expression evaluation" << std::endl; std::cout << "Not using safe numerics" << std::endl; try{ std::int8_t x = 127; std::int8_t y = 2; std::int8_t z; // this produces an invalid result ! z = x + y; std::cout << "error NOT detected!" << std::endl; std::cout << (int)z << " != " << (int)x << " + " << (int)y << std::endl; } catch(const std::exception &){ std::cout << "error detected!" << std::endl; } // solution: replace int with safe<int> std::cout << "Using safe numerics" << std::endl; try{ using namespace boost::safe_numerics; safe<std::int8_t> x = INT_MAX; safe<std::int8_t> y = 2; safe<std::int8_t> z; // rather than producing an invalid result an exception is thrown z = x + y; } catch(const std::exception & e){ // which we can catch here std::cout << "error detected:" << e.what() << std::endl; } return 0; }


example 1:undetected erroneous expression evaluation
Not using safe numerics
error NOT detected!
-127 != 127 + 2
Using safe numerics
error detected:converted signed value too large: positive overflow error