使用计数器的智能指针模板例子

基类Uc_object 如下:

class Uc_object
{
private:
	unsigned int count_d;
public:
	Uc_object():count_d(0){}
	Uc_object(const Uc_object&):count_d(0){}
	virtual ~Uc_object(){}
	void increment(){++count_d;}
	void decrement()
	{
		if (--count_d==0)
		{
			delete this;
		}
	}
	unsigned int use_count()
	{
		return count_d;
	}
};

 

模板类Uc_ptr如下:

template <class T>
class Uc_ptr
{
private:
	T* ptr;
public:
	Uc_ptr(T* =0);
	Uc_ptr(const Uc_ptr<T>& );
	~Uc_ptr();
	const Uc_ptr<T>& operator=(const Uc_ptr<T>&);
	operator T*()const {return ptr;}
	T* operator->()const {return ptr;}
};

模板类Uc_ptr的实现如下:

template <class T>
Uc_ptr<T>::Uc_ptr(T* arg):ptr(arg)
{
	if(ptr)
		ptr->increment();
}

template <class T>
Uc_ptr<T>::Uc_ptr(const Uc_ptr<T>& arg):ptr(arg.ptr)
{
	if (ptr)
	{
		ptr->decrement();
	}
}

template<class T>
Uc_ptr<T>::~Uc_ptr()
{
	if (ptr)
	{
		ptr->decrement();
	}

}

template<class T> const Uc_ptr<T>& Uc_ptr<T>::operator=(const Uc_ptr<T>& arg) {

 if(ptr)  {   ptr->decrement();  }  if (ptr=arg.ptr)  {   ptr->increment();  }  return *this;

}


使用Uc_ptr来实现rep 类

class String_rep:public Uc_object
{
	friend class String;
	char* data;
	String_rep(const char* cp);
	~String_rep();
};


rep的实现如下:

String_rep::String_rep(const char* cp):data(new char[strlen(cp)+1])
{
	strcpy(data,cp);
}

String_rep::~String_rep()
{
	delete []data;
}


String 类的实现如下:

class String 
{
private:
	Uc_ptr<String_rep> rep;
public:
	String(const char* cp=""):rep(new String_rep(cp))
	{

	}
	void printStr()
	{
		printf("%s",rep->data);
	}
};


我们可以随便写个测试代码来测试这个使用了计数器的智能指针模板

int _tmain(int argc, _TCHAR* argv[])
{
	String a=String("heping");
	a.printStr();

	return 0;
}


 



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值