跟踪与调试

2014-11-24 09:08:25 · 作者: · 浏览: 0

/*
许多C++程序员在跟踪代码时通常的做法是,定义一个简单的Trace类将诊断信息打印到日志文件中。程序员
可以在每个想要跟踪的函数中定义一个Trace对象,在函数的入口和出口Trace类可以分别写一条信息。
缺点:增加程序开销,必须重新编译程序来打开或关闭跟踪。
*/
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 < }
}

inline Trace::debug(const string &msg)
{
if (traceIsActive)
{
cout << msg < }
}

inline Trace::~Trace()
{
if (traceIsActive)
{
cout << "Exit function " << theFunctionName < }
}

int myFunction(int x)
{
#ifdef TRACE
Trace t("myFunction"); //构造函数以一个函数名作为参数。
t.debug("Some information message");
#endif

}

//以上的代码存在性能问题,优化版:
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 < theFunctionName = new string(*name);
}
}

inline Trace::debug(const char* msg)
{
if (traceIsActive)
{
cout << *msg < }
}

inline Trace::~Trace()
{
if (traceIsActive)
{
cout << "Exit function " << *theFunctionName < delete theFunctionName;
}
}

int myFunction(int x)
{
#ifdef TRACE
char* name = "myFunction";
Trace t(name); //构造函数以一个函数名作为参数。
#endif

}