您的位置:首页 > 编程语言 > C语言/C++

C++内存管理--简单的引用计数的实现

2014-04-16 11:22 351 查看
共享指针的内存对象,往往用引用计数来管理,多线程的环境下还得考虑锁同步

写了一个简单实现,上代码:

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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: