Friday, October 30, 2009

Using a Plain Old String: Single-Threaded




I l@ve RuBoard









Using a Plain Old String: Single-Threaded


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



    No comments: