#include <cassert>
/** 引用计数类*/
class IBase
{
public:
IBase(void) : m_bManaged_(true),m_nRefCounter_(0) { };
virtual ~IBase(void) { }
/** 增加引用计数*/
void addRef(void) { ++m_nRefCounter_; }
/** 减少引用计数*/
void delRef(void)
{
--m_nRefCounter_;
if (m_nRefCounter_<=0 && m_bManaged_)
{
destroyThis();
}
}
/** 获得引用计数*/
int getRef(void){ return m_nRefCounter_; }
bool isRefUnique(){ return m_nRefCounter_ == 1; }
public://属性
/*设置资源管理。*/
void setManaged(bool m){ m_bManaged_ = m; }
bool getManaged(void){ return m_bManaged_ ; }
virtual void destroyThis(void){ delete this; }
private:
bool m_bManaged_ ; //自动管理资源
int m_nRefCounter_ ;//引用计数
};
/** 侵入式智能指针*/
template<typename T>
class RefPtr
{
public:
typedef T type;
typedef RefPtr<type> ThisType;
RefPtr()
: m_ptr(nullptr)
{
}
RefPtr(type* ptr)
: m_ptr(ptr)
{
safeAddRef(m_ptr);
}
RefPtr(const ThisType & ptr)
: m_ptr(ptr.m_ptr)
{
safeAddRef(m_ptr);
}
template<class U>
RefPtr(const RefPtr<U> & ptr)
{
m_ptr = dynamic_cast<T*>(ptr.get());
safeAddRef(m_ptr);
}
~RefPtr(void)
{
safeDelRef(m_ptr);
}
public:
type* operator->() const
{
assert(m_ptr && "smartptr is null!");
return m_ptr;
}
type& operator*() const
{
assert(m_ptr && "smartptr is null!");
return *m_ptr;
}
operator bool() const
{
return (m_ptr != nullptr);
}
type* get() const
{
return m_ptr;
}
const ThisType & operator=(type* ptr)
{
if (ptr != m_ptr) //防止自复制
{
safeAddRef(ptr);
safeDelRef(m_ptr);
m_ptr = ptr;
}
return *this;
}
const ThisType & operator=(const ThisType & ptr)
{
return *this = ptr.m_ptr;
}
///强制类型转换
template<typename U>
const ThisType & operator=(U* ptr)
{
return *this = dynamic_cast<type*>(ptr);
}
///强制类型转换
template<typename U>
const ThisType & operator=(const RefPtr<U> & ptr)
{
return *this = dynamic_cast<type*>(ptr.get());
}
private:
inline void safeAddRef(type * ptr)
{
if (ptr != nullptr)
{
ptr->addRef();
}
}
inline void safeDelRef(type * ptr)
{
if (ptr != nullptr)
{
ptr->delRef();
}
}
type* m_ptr;
};
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, const RefPtr<U>& b)
{
return (a.get() == b.get());
}
template<typename T>
bool operator==(const RefPtr<T>& a, const T* b)
{
return (a.get() == b);
}
template<typename T>
bool operator==(const T* a, const RefPtr<T>& b)
{
return (a == b.get());
}
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b)
{
return (a.get() != b.get());
}
template<typename T>
bool operator!=(const RefPtr<T>& a, const T* b)
{
return (a.get() != b);
}
template<typename T>
bool operator!=(const T* a, const RefPtr<T>& b)
{
return (a != b.get());
}
#endif //LAZY3D_REFPTR_H
智能指针
最新推荐文章于 2025-05-17 12:51:21 发布