C++沉思录读书笔记(27章)- 设计自己跟踪自己的类

这篇文章的目的是设计提供有关函数执行和类操作调试信息的类


1.一个简单函数跟踪类的设计

class Trace   //跟踪类
{
public:
	Trace(const char* p, const char* q): bye(q) { cout << p; }
	~Trace() { cout << bye; }
private:
	const char* bye;
};

//使用示范
void foo()
{
	Trace xx("begin foo\n", "end foo\n");
	...
}

int main()
{
	foo();
	//...
}

我们可能想拥有一个调试开关,也可能想在别的地方输出调试信息,于是上述的跟踪类可以改进如下:

class Channel   //输出重定向类
{
public:
	Channel(ostream* os = &cout) : Trace_File(os) { }
	void Reset(ostream *os) { Trace_File = os;}
private:
	friend class Trace;
	ostream* Trace_File;
};

static const int debug = 1;  //debug控制开关
class Trace  //跟踪类
{
public:
	Trace(const char *s, Channel *c) : m_name(s), m_cp(c)
	{
		if(debug)
			if (m_cp->Trace_File)
			*m_cp->Trace_File<<"begin"<<m_name<<endl;
	}
	~Trace()
	{
		if(debug)
			if (m_cp->Trace_File)
			*m_cp->Trace_File<<"end"<<m_name<<endl;
	}
private:
	Channel *m_cp;
	const char* m_name;
};

//使用示范
Channel subsystemX;
subsystemX.reset(0) //关闭跟踪
subsystemX.reset(&some_stream) //重定向跟踪
void foo()
{
	Trace xxx("foo", &subsystemX);
	//...
}

int main()
{
	foo();
	//...
}


2.一个对象生成的审计跟踪类的设计
代码如下:

#include <iostream>
using namespace std;
class Obj_trace
{
public:
	Obj_trace():ct(++count) { cout<<"Object "<<ct<<" constructed"<<endl; }
	~Obj_trace() { cout<<"Object "<<ct<<" destructed"<<endl; }
	Obj_trace(const Obj_trace&):ct(++count) { cout<<"Object"<<ct<<" constructed"<<endl; }
	Obj_trace& operator=(const Obj_trace&) { return *this; }
private:
	static int count;
	int ct;
};
int Obj_trace::count = 0;

template<class T>class Array
{
public:
	Array(int n = 0):data(new T[n]), sz(n) {}
	Array(const Array& a) { Init(a.data, a.sz); }
	~Array() { delete[] data; }
	Array& operator=(const Array& a)
	{
		if (this != &a)
		{
			delete[] data;
			Init(a.data, a.sz);
		}
		return *this;
	}
	T& operator[](unsigned int index)
	{
		return data[index];
	}
private:
	T* data;
	int sz;
	void Init(T*, int);
};

template<class T>void Array<T>::Init(T* p, int n)
{
	sz = n;
	data = new T[n];
	for (int i=0; i<sz; ++i)
	{
		data[i] = p[i];
	}
}

int main()
{
	Array<Obj_trace> x(3);
	Array<Obj_trace> y = x;
	//y = x;//测试赋值
	return 0;
}
运行结果如下:

Object 1 constructed
Object 2 constructed
Object 3 constructed
Object 4 constructed
Object 5 constructed
Object 6 constructed
Object 6 destructed
Object 5 destructed
Object 4 destructed
Object 3 destructed
Object 2 destructed
Object 1 destructed


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值