现在的位置: 首页 > 综合 > 正文

C++智能指针

2013年08月25日 ⁄ 综合 ⁄ 共 1293字 ⁄ 字号 评论关闭

在设计有指针成员的类时,当我们把一个指针成员复制给另外一个类对象的指针成员时,他们的指针成员共同指向内存中的同一对象,可以使用任意一个指针更改内存中的这个对象。我们把内存中的这个对象叫做共享对象。但是当一个指针删除了这个共享对象时,另一个指针不知道这个对象已经不存在了,它仍然会读写这个共享对象所在的内存单元,这就造成了严重的安全问题。这时我们可以采用智能指针来管理这个共享对象,用户仍然可以通过普通指针访问这个共享对象,但是不能删除它,智能指针将保证在撤销最后一个指向共享对象的对象时删除该共享对象。说着麻烦,直接上代码,看了就明白了

#include<iostream>

using namespace std;

class uptr
{
	friend class hasptr;				//定义hasptr为友元类,只有hasptr可以访问uptr
	int *ip;
	size_t use;							//共享对象使用计数 
	uptr(int *p):ip(p),use(1){}
	~uptr(){delete ip;}
};

class hasptr
{
	public:
	hasptr(int *p,int i):ptr(new uptr(p)),val(i){}
	hasptr(const hasptr&other):ptr(other.ptr),val(other.val){++ptr->use;}
	hasptr & operator=(const hasptr&other)
	{
		++other.ptr->use;				// 增加uptr的使用计数 
		if(--ptr->use==0)				//this->ptr之前可能指向其它的uptr,所以this->ptr->use减一 
			{
				delete ptr;
			}
		ptr=other.ptr;
		val=other.val;
		return *this;
	}
	~hasptr()
	{
		if(--ptr->use==0) delete ptr;	//当--ptr->use为零时,说明本对象是最后一个使用共享对象的 
	}
	int *getptr(){return ptr->ip;}
	int getval(){return val;}
	void setptr(int *p){ptr->ip=p;}
	void setval(int i){val=i;}
	int getptrval(){return *ptr->ip;}
	void setptrval(int i){*ptr->ip=i;}
	private:
	uptr *ptr;
	int val;
};

int main()
{
	int *p=new int(42);
	hasptr has1(p,10);
	hasptr has2=has1;
	cout<<"has1的val数值为:"<<has1.getptrval()<<endl;
	cout<<"has2的val数值为:"<<has2.getptrval()<<endl;
	delete p;
	has1.setptrval(1);
	cout<<"has1的val数值为:"<<has1.getptrval()<<endl;
	cout<<"has2的val数值为:"<<has2.getptrval()<<endl;
}

如果复制has1则对象如下图所示

抱歉!评论已关闭.