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

share_ptr 引用计数的实现

2014-08-17 21:13 344 查看
        智能指针在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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  智能指针 C++ boost std tr1