智能指针实现

4 篇文章 0 订阅

当类中有指针成员时,一般有两种方式来管理指针成员:一是采用值型的方式管理,每个类对象都保留一份指针指向的对象的拷贝;另一种更优雅的方式是使用智能指针,从而实现指针指向的对象的共享。
智能指针(smart pointer)的一种通用实现技术是使用引用计数(reference count)。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象的指针指向同一对象。

智能指针主要是通过引用技术的原理,封装指针本身,需要有复制构造函数,重载=,*,->等,通过模板类来实现,再深入一点,可以自由决定是否复制指针所指的对象,参考accelerated c++

#include<iostream>
#include<cstdlib>
using namespace std;
class test{
private:
	int data;
	char name[20];
public :
	test()
	{
		data=0;
		strcpy(name,"");
	}
	test(int d,char *n)
	{
		data=d;
		strcpy(name,n);
	}
	void show(){
		cout<<data<<name<<endl;
	}
	void set(int data,char *n)
	{
		this->data=data;
		strcpy(name,n);
	}
};
template <class t>
class smart_ptr
{
private :
	t *ptr;
	size_t *count;
public :
	smart_ptr()
	{
		ptr=NULL;
		count=new size_t(1);
	}
	smart_ptr(t *p)
	{
		ptr=p;
		count=new size_t(1);
	}
	smart_ptr(const smart_ptr &c){
		ptr=c.ptr;
		this->count=c.count;//计数以及p本身全部要复制
		++*count;
	}
	smart_ptr & operator=(const smart_ptr &c)
	{
		//=,引用技术,要防止自身到自身的
		//增加引用计数
		++*c.count;
		if(--*count==0)
		{
			delete count;
			delete ptr;
		}
		ptr=c.ptr;
		count=c.count;
		return *this;

	}
	int get_count()
	{
		return *count;
	}
	t & operator*()
	{
		if(ptr) {
			return *ptr;
		}
		else
			throw runtime_error("NULL");
	}
	t *operator->()
	{
		if(ptr){
			return ptr;
		}
		throw runtime_error("NULL");
	}
	~smart_ptr(){
		if(--*count==0){
			delete count;
			delete ptr;
			count=NULL;
			ptr=NULL;
		}
	}



};


int main(){
	int data=2;

	smart_ptr<test> a1=new test(1,"hdu");
	a1->show();
	smart_ptr<test> a2(new test(2,"hdu"));
	a2->show();
	smart_ptr<test> a3(a1);
	(*a3).show();
	a2=a1;
	a2->show();
	int count=a1.get_count();
	cout<<count<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值