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; };
相关文章推荐
- share_ptr 实现c++ 句柄引用计数
- 实现类似shared_ptr的引用计数
- 引用计数的智能指针——sharedptr的模拟实现
- linux-2.6内核模块引用计数的实现
- linux-2.6内核模块引用计数的实现
- boost库在工作(9)引用计数的智能指针shared_ptr之二
- boost库在工作(12)引用计数的智能指针intrusive_ptr
- boost库在工作(12)引用计数的智能指针intrusive_ptr
- 一种引用计数机制的实现
- 带引用计数的String类简单实现
- 如何实现引用计数对象
- 一种基于引用计数机制的智能指针实现
- linux-2.6内核模块引用计数的实现(try_module_get和module_put)
- linux-2.6内核模块引用计数的实现
- 在smart_ptr中处理引用计数时使用swap概念(boost::shared_ptr.hpp)
- boost库在工作(9)引用计数的智能指针shared_ptr之二
- linux-2.6内核模块引用计数的实现
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- ATL学习笔记(1):ATL单线程与多线程套间对象引用计数的基础实现
- 引用计数的智能指针的实现与思考