/*
When tracking code, many C ++ programmers often define a simple Trace class to print diagnostic information to a log file. Programmer
You can define a Trace object in each function to be tracked. You can write a Trace object in the function Entry and Exit Trace classes.
Disadvantage: To increase program overhead, you must recompile the program to open or close the tracing.
*/
Class Trace
{
Public:
Trace (conse string & name );
~ Trace (); www.2cto.com
Void debug (const string & msg );
Static BOOL traceIsActive;
Private:
String theFunctionName;
};
Inline Trace: Trace (const string & name): theFunctionName (name)
{
If (traceIsActive)
{
Cout <"Enter function" <name <endl;
}
}
Inline Trace: debug (const string & msg)
{
If (traceIsActive)
{
Cout <msg <endl;
}
}
Inline Trace ::~ Trace ()
{
If (traceIsActive)
{
Cout <"Exit function" <theFunctionName <endl;
}
}
Int myFunction (int x)
{
# Ifdef TRACE
Trace t ("myFunction"); // The constructor uses a function name as a parameter.
T. debug ("Some information message ");
# Endif
}
// The above code has performance problems. Optimized version:
Class Trace
{
Public:
Trace (const char * name );
~ Trace ();
Void debug (const char * msg );
Static BOOL traceIsActive;
Private:
String * theFunctionName;
};
Inline Trace: Trace (const char * name): theFunctionName (NULL)
{
If (traceIsActive)
{
Cout <"Enter function" <* name <endl;
TheFunctionName = new string (* name );
}
}
Inline Trace: debug (const char * msg)
{
If (traceIsActive)
{
Cout <* msg <endl;
}
}
Inline Trace ::~ Trace ()
{
If (traceIsActive)
{
Cout <"Exit function" <* theFunctionName <endl;
Delete theFunctionName;
}
}
Int myFunction (int x)
{
# Ifdef TRACE
Char * name = "myFunction ";
Trace t (name); // The constructor uses a function name as a parameter.
# Endif
}