📄 usercount.h
字号:
#ifndef _USERCOUNT_H_
#define _USERCOUNT_H_
#include "thread.h"
#include <cassert>
namespace mylib{
//////////////////////////////////////////////////////////////////////
//引用计数和T*分离,单线程
//////////////////////////////////////////////////////////////////////
class Usecount
{
public:
Usecount();
Usecount(const Usecount& use);
~Usecount();
bool Only(){ return *ref == 1; }
bool MakeOnly();
bool ReAttach(const Usecount&);
int GetCurCount() const {return *ref;}
private:
int *ref;
Usecount& operator=(const Usecount& use);
};
template <typename T>
class HandleP
{
public:
//就算m_p是0,也可以delete
HandleP(T *p=0):m_p(p){}
HandleP(const HandleP &tmp):m_Ref(tmp.m_Ref),m_p(tmp.m_p){}
HandleP& operator=(const HandleP &tmp);
~HandleP();
public://原接口
T* operator->()
{ return m_p;}
private:
T *m_p;
Usecount m_Ref;
};
template <typename T>
HandleP<T>::~HandleP<T>()
{
bool bOnly=m_Ref.Only();
if(bOnly)
delete m_p;
m_p=0;
}
template <typename T>
HandleP<T>& HandleP<T>::operator=(const HandleP<T> &tmp)
{
bool bIsNew=m_Ref.ReAttach(tmp.m_Ref);
if(bIsNew)
//就算m_p是0,也可以delete
//assert(m_p==0);
delete m_p;
m_p=tmp.m_p;
return *this;
}
//////////////////////////////////////////////////////////////////////
//引用计数和T*绑定,MT-SAFE
//////////////////////////////////////////////////////////////////////
template <typename T>
class CTh_HandleP
{
private:
class C_counted_base
{
public:
C_counted_base(T* pp):m_p(pp),use_count_(1),mtx_(){}
~C_counted_base() {}
void AddRef();
long ReleaseRef();
long GetCount() const;
public:
T *m_p;
private:
C_counted_base(C_counted_base const &);
C_counted_base & operator= (C_counted_base const &);
long use_count_; // #shared
CThMutex mtx_;
};
public:
//就算m_p是0,也可以delete
CTh_HandleP(T *p=0):m_u( new C_counted_base(p) ){ }
CTh_HandleP(const CTh_HandleP &r)
{
m_u = r.m_u;
m_u->AddRef();
}
CTh_HandleP& operator=(const CTh_HandleP &r);
~CTh_HandleP( )
{
if(m_u != 0) m_u->ReleaseRef();
}
public://原接口
T* operator->()
{
assert(m_u->m_p);
return m_u->m_p;
}
private:
C_counted_base* m_u;
};
template <typename T>
void CTh_HandleP<T>::C_counted_base::AddRef()
{
AutoMutex lock(mtx_);
++use_count_;
}
template <typename T>
long CTh_HandleP<T>::C_counted_base::ReleaseRef()
{
long new_use_count;
{
AutoMutex lock(mtx_);
new_use_count = --use_count_;
}
if(new_use_count !=0)
return new_use_count;
else
{
delete m_p;
delete this;
return 0;
}
}
template <typename T>
long CTh_HandleP<T>::C_counted_base::GetCount() const
{
AutoMutex lock(mtx_);
return use_count_;
}
template <typename T>
CTh_HandleP<T>& CTh_HandleP<T>::operator=(const CTh_HandleP<T> &r)
{
C_counted_base* tmp = r.m_u;
if(tmp != 0) tmp->AddRef();
if(m_u != 0) m_u->ReleaseRef();
m_u = tmp;
return *this;
}
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -