智能指针在c++标准库中提供了auto_ptr,但是,只允许一个有一个实例指向资源,但有些时候这样子是不符合需求的,在tr1中提供了一个新的共享智能指针,share_ptr,其中使用了引用计数。以下是简单的实现。
template <typename _Ty>
class kshare_ptr
{
public:
kshare_ptr(_Ty* _t = NULL)
: m_Ty(_t)
{
m_pRef = new size_t(1);
}
~kshare_ptr()
{
--*m_pRef;
if (*m_pRef == 0)
{
delete m_pRef;
m_pRef = NULL;
delete m_Ty;
m_Ty = NULL;
}
}
kshare_ptr(const kshare_ptr<_Ty>& _rhs)
{
m_pRef = _rhs.m_pRef;
++*m_pRef;
m_Ty = _rhs.m_Ty;
}
kshare_ptr& operator=(const kshare_ptr<_Ty>& _rhs)
{
if (this == &_rhs)
{
return *this;
}
--*m_pRef;
if (m_pRef == 0)
{
delete this;
}
++*_rhs.m_pRef;
m_Ty = _rhs.m_Ty;
return *this;
}
public:
_Ty* m_Ty;
size_t* m_pRef;
};