//智能指针类
//----------------------------------------
//1.基数据放在使用计数类中
//实际类指向->使用计数类->基数据
//使用计数类
class U_ptr{
friend class Hasptr;//友元类
int *ip;//这个就是要保护的基数据
size_t use;
U_ptr(int *p):ip(p),use(1){}
~U_ptr(){delete ip;}
};
class Hasptr//实际类
{
public:
Hasptr(int *p,int i):ptr(new U_ptr((p)),val(i){}
Hasptr(const Hasptr &orig):ptr(orig.ptr),val(orig.val){++ptr->use;}
Hasptr& operator=(const Hasptr &rhs){
++rhs.ptr->use;
if (--ptr->use == 0)
delete ptr;
ptr=rhs.ptr;
val=rhs.val;
return *this;
}
~Hasptr(){if(--ptr->use == 0)delete ptr;}
private:
U_ptr *ptr;
int val;
};
//----------------------------------------------
//2.基数据放在实际类中
//实际类指向使用计数类,实际类还指向同一个基数据
//使用计数类
class U_ptr{
friend class Hasptr;//友元类
size_t use;
U_ptr():use(1){}
~U_ptr(){}
};
class Hasptr//实际类
{
public:
Hasptr(int *p,int i):ptr(new U_ptr),ip(p)val(i){}
Hasptr(const Hasptr &orig):ptr(orig.ptr),ip(orig.p);val(orig.val){++ptr->use;}
Hasptr& operator=(const Hasptr &rhs){
++rhs.ptr->use;
if (--ptr->use == 0){
delete ptr;
delete ip;
}
ptr=rhs.ptr;
ip=rhs.ip;
val=rhs.val;
return *this;
}
~Hasptr(){
if(--ptr->use == 0){
delete ptr;
delete ip;
}
}
private:
int *ip;//这个就是要保护的基数据
U_ptr *ptr;
int val;
};
//定义值型类
//复制对象时,同时复制指针所指向的基数据
智能指针类
最新推荐文章于 2023-07-23 17:30:16 发布