Using a Plain Old String: Single-Threaded

I l @ ve RuBoard

Say we want our program to keep track of the last error message we encountered and automatically decorate it with the time the message was generated. We might implement it using a global string value with helper functions to get and set the state:

 // Example A-1: A simple error recording subsystem // String err; int count = 0; String GetError() {   return err; } String SetError( const String& msg ) {   err = AsString( ++count ) + ": ";   err += msg;   err += " (" + TimeAsString() + ")";   return err; } 

As long as our program is single-threaded, we never have to worry about Get-Error() or SetError() being called at the same time on different threads, so all is well. For example, given:

 String newerr = SetError( "A" ); newerr += " (set by A)"; cout << newerr << endl; // ...later... // newerr = SetError( "B" ); newerr += " (set by B)"; cout << newerr << endl; 

the output would be something like:

 1: A (12:01:09.65) (set by A) 2: B (12:01:09.125) (set by B) 
I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net