Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 20

void processUserCommand(UserCommand& cmd)

{

// Details omitted for brevity

}

void trickyFunction(ComplicatedClass* obj) throw(exception)

{

assert(obj != NULL);

// Trace log the values with which this function starts. ostringstream ostr;

ostr << “trickyFunction(): given argument: “ << *obj; debugBuf.addEntry(ostr.str());

while (true) {

UserCommand cmd = getNextCommand(obj);

ostringstream ostr;

ostr << “trickyFunction(): retrieved cmd “ << cmd; debugBuf.addEntry(ostr.str());

try { processUserCommand(cmd);

} catch (exception& e) {

string msg = “trickyFunction(): received exception from procesUserCommand():”;

msg += e.what(); debugBuf.addEntry(msg); throw;

}

break;

}

}

Note that this interface to the ring buffer sometimes requires you to construct strings using ostringstreams or string concatenation before adding entries to the buffer.

Displaying the Ring Buffer Contents

Storing trace debug messages in memory is a great start, but in order for them to be useful, you need a way to access these traces for debugging. Your program should provide a “hook” to tell it to print the messages. This hook could be similar to the interface you would use to enable debugging at run time.

Additionally, if your program encounters a fatal error that causes it to exit, it should print the ring buffer to standard error or to a log file before exiting.

Another way to retrieve these messages is to obtain a memory dump of the program. Each platform handles memory dumps differently, so you should consult a book or expert on your platform.

Asserts

The assert macro in the <cassert> library is a powerful tool. It takes a Boolean expression and, if the expression evaluates to false, prints an error message and terminates the program. If the expression evaluates to true, it does nothing. Although this behavior may not sound particularly helpful, it turns

540