After reading some threads on misuses of exceptions (basically saying you don’t want to unwind the stack if a functions preconditions are incorrect – possibly signalling that all your memory is corrupt or something equally dangerous) I’m thinking about using assert() more often. Previously I have only used assert() as a debug tool and I think this is how a lot of C++ programmers use it. I’m concerned about part of my error handling being turned off by a NDEBUG #define introduced to the runtime builds at some point in the future. Is there a way round this and have others had a problem with this (i.e. should I be worrying about it)?
Thanks, Pat
Edit: The point of the threads I was reading was that if your application is truely buggered then unwinding stack could damage the system, for instance if a destructor wrote something to a file and the file handle was corrupted. I’m not suggesting using assert for normal error handling. The current use case I have is pretty weak but see what you think:
//check later code won't crash the system if( buf.length() % 2 ) return false; // do other stuff that shouldn't affect bufs length //copy 2 bytes into buf at a time, if length is odd then don't know //what will happen so use assert to make sure it can't damage anything assert( !(buf.length() % 2) ); for( i = 0; i != buf.length(); i += 2 ) memcpy( buf + i, data, 2 );
edit2: the discussion is here: http://groups.google.com/group/comp.lang.c++.moderated/browse_frm/thread/80083ac31a1188da
You could build your own assert instead of using the stock C assert.h. Your assert won’t be disabled.
Look at how assert() is implemented in /usr/include/assert.h (or wherever). It’s simply some preprocessor magic eventually calling an ‘assert fail’ function.
In our embedded environments, we replace assert() all the time.