c++中的引用计数
来源:互联网 发布:智多星造价软件多少钱 编辑:程序博客网 时间:2024/06/08 08:34
#ifndef SHARED_PTR_H_ #define SHARED_PTR_H_ #ifndef NULL #define NULL 0 #endif namespace util { template <class T> class shared_ptr; template <class T> class shared_data { private: friend class shared_ptr<T>; explicit shared_data(T *pT): _M_ptr(pT) { _M_nCount = 1; } ~shared_data() { delete _M_ptr; } void operator++() { ++_M_nCount; } void operator--() { --_M_nCount; if (_M_nCount == 0) { delete this; } } T &operator *()const { return *_M_ptr; } T *operator->()const { return _M_ptr; } bool operator == (T *pT)const { return _M_ptr == pT; } T *get() { return _M_ptr; } int use_count() { return _M_nCount; } private: T *_M_ptr; unsigned int _M_nCount; }; template <class T> class shared_ptr { typedef shared_data<T> element; public: explicit shared_ptr(T *pT): _M_pD(NULL) { _M_pD = new element(pT); } explicit shared_ptr(): _M_pD(NULL) { } // copy constructor shared_ptr(const shared_ptr < T > &rT) { _M_pD = rT.get_element(); if (_M_pD != NULL) { ++(*_M_pD); } } ~shared_ptr() { if (_M_pD != NULL) { --(*_M_pD); } } // assignment operator shared_ptr < T > &operator = (const shared_ptr < T > &rT) { if (_M_pD != NULL) { --(*_M_pD); } _M_pD = rT.get_element(); if (_M_pD != NULL) { ++(*_M_pD); } return *this; } // assignment operator shared_ptr < T > &operator = (shared_ptr < T > &rT) { if (_M_pD != NULL) { --(*_M_pD); } _M_pD = rT.get_element(); if (_M_pD != NULL) { ++(*_M_pD); } return *this; } T &operator *()const { return _M_pD->operator *(); } T *operator->()const { return _M_pD->operator->(); } bool operator == (shared_ptr < T > &rT)const { return rT.get_element() == _M_pD; } bool operator == (T *pT)const { if (_M_pD == NULL) { return pT == NULL; } return *_M_pD == pT; } T *get() { if (_M_pD == NULL) { return NULL; } else { return _M_pD->get(); } } void release() { if (_M_pD != NULL) { --(*_M_pD); _M_pD = NULL; } } void reset(T *pT) { if (_M_pD != NULL) { --(*_M_pD); _M_pD = NULL; } _M_pD = new element(pT); } private: element *get_element()const { return _M_pD; } element *_M_pD; }; } #endif
阅读全文
0 0
- Python/C API中的引用计数修改
- Python中的引用计数
- c++中的引用计数
- c++中的引用计数
- objective-c 引用计数
- Effective c++:引用计数
- 【c++】引用计数
- Objective-C 引用计数
- 【C++】引用计数
- 监控Python中的引用计数
- delphi中的引用计数接口
- more effective c++--引用计数
- Objective-C 引用计数原理
- Objective-C 引用计数原理
- Objective-C 引用计数原理
- objective-c中的内存管理——引用计数、ARC与MRC(1)
- COM 中的 引用计数和AddRef、Release
- cocos2d-x中的引用计数原理
- 学习总结----redis
- Eclipse一闪而过的问题解决
- CentOS 6.5下快速搭建ftp服务器
- 递归函数的堆栈实现
- shadowsocks使用教程
- c++中的引用计数
- [总结]C++真是博大精深(二)
- Python常见error
- const 是个类型修饰符号。
- SHA1/MD5/URLDECODE 在php审计题中的一般思路(积累中)
- 最小k限度生成树 +poj(1639)代码
- 帮我看看这个是什么意思 c++代码
- 流媒体开发: RTSP协议学习
- 遇到了WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!