共享指针的内存对象,往往用引用计数来管理,多线程的环境下还得考虑锁同步
写了一个简单实现,上代码:
class Hasptr;
class Use_ref
{
friend Hasptr;
int *area;
unsigned ref;
Use_ref(int *p):area(p),ref(1){}
~Use_ref(){delete area;}
};
class Hasptr
{
public:
Hasptr(int *p,int i):ptr(new Use_ref(p)){}
Hasptr(const Hasptr &other):ptr(other.ptr){++ptr->ref;}
Hasptr &operator=(const Hasptr & other)
{
if(this!=&other)
{
ptr=other.ptr;
++ptr->ref;
}
return *this;
}
~Hasptr()
{
if(--ptr->ref==0)
delete ptr;
}
private:
Use_ref *ptr;
};