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

来源:互联网 发布:中日网络战 编辑:程序博客网 时间:2024/05/22 01:34

共享指针的内存对象,往往用引用计数来管理,多线程的环境下还得考虑锁同步

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

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;};





0 0