![]() |
Home | Libraries | People | FAQ | More |
A simple assign or arithment expression will generally convert all
the terms to the same type. Sometimes this can silently change values. For
example, when a signed data variable contains a negative type, assigning
to a unsigned type will be permitted by any C/C++ compiler but will be
treated as large unsigned value. Most modern compilers will emit a compile
time warning when this conversion is performed. The user may then decide
to change some data types or apply a static_cast. This is
less than satisfactory for two reasons:
It may be unwield to change all the types to signed or unsigned.
Litering one's program with static_cast
makes it more difficult to read.
We may believe that our signed type will never contain a
negative value. If we use a static_cast to suppress the
warning, we'll fail to detect a program error when it is commited.
This is aways a risk with casts.
This solution is the same as the above, Just replace instances of
the int with safe<int>.
void example2(){
// problem: undetected overflow in data type
try{
int x = INT_MAX;
// the following silently produces an incorrect result
++x;
//std::cout << x << " != " << -1;
detected_msg(false);
}
catch(...){
assert(false); // never arrive here
}
// solution: replace int with safe<int>
try{
using namespace boost::numeric;
safe<int> x = INT_MAX;
// throws exception when result is past maximum possible
++x;
assert(false); // never arrive here
}
catch(std::range_error & e){
std::cout << e.what();
detected_msg(true);
}
}