BODY { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } P { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } DIV { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } TD { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } 使用智能指针的一个示例
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
{
private:
U_Ptr *ptr;
int val;
public:
int *get_ptr() const{ return ptr->ip;}
int get_ptr_val() const{ return *ptr->ip;}
int get_val() const { return val;}
void set_int(int i) {val = i;}
void set_ptr(int *p) { ptr->ip = p;}
void set_ptr_val(int i){ *ptr->ip=i; }
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?
~HasPtr(){if(--ptr->use==0) delete ptr;}
};
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++rhs.ptr->use;
if(--ptr->use==0)
delete ptr;
ptr=rhs.ptr;
val=rhs.val;
return *this;
}
{
friend class HasPtr;
int *ip;
size_t use;
U_Ptr(int *p):ip(p),use(1){}
~U_Ptr() { delete ip;}
};
class HasPtr
{
private:
U_Ptr *ptr;
int val;
public:
int *get_ptr() const{ return ptr->ip;}
int get_ptr_val() const{ return *ptr->ip;}
int get_val() const { return val;}
void set_int(int i) {val = i;}
void set_ptr(int *p) { ptr->ip = p;}
void set_ptr_val(int i){ *ptr->ip=i; }
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?
~HasPtr(){if(--ptr->use==0) delete ptr;}
};
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++rhs.ptr->use;
if(--ptr->use==0)
delete ptr;
ptr=rhs.ptr;
val=rhs.val;
return *this;
}