智能指正和强弱指针的实现
来源:互联网 发布:mips linux gnu gcc 编辑:程序博客网 时间:2024/06/06 12:46
#include <iostream>#include <map>#include <pthread.h>using namespace std;class maps_ptr{public: static maps_ptr * getptr() { if(inst==NULL) { inst=new maps_ptr(); } return inst; } void addRef(void *mptr) { map<void *,int>::iterator it=a.find(mptr); if(it!=a.end()) { it->second++; return ; } a.emplace(mptr,1); } void delRef(void *mptr) { map<void *,int>::iterator it=a.find(mptr); if(it!=a.end()) { it->second--; if(it->second==0) { a.erase(it); } } } int getRef(void *mptr) { map<void *,int>::iterator it=a.find(mptr); if(it!=a.end()) { return it->second; } return 0; }private: maps_ptr() {}; static maps_ptr *inst; map<void *,int> a;};maps_ptr* maps_ptr::inst=NULL;template <typename T>class Cweak;template <typename T>class smart_ptr{public: smart_ptr(T* ptr=NULL):mptr(ptr) { if(mptr!=NULL) { a->addRef(mptr); } }; ~smart_ptr() { a->delRef(mptr); if(a->getRef(mptr)==0) { delete mptr; } } smart_ptr(const smart_ptr &src) { if(src.mptr!=NULL) { mptr=src.mptr; a->addRef(mptr); } else { mptr=NULL; } } smart_ptr<T> (const Cweak<T> &src) { if(a->getRef(mptr)!=0) { mptr=src.mptr; a->addRef(mptr); } else { mptr=NULL; } } smart_ptr<T>& operator =(const smart_ptr &src) { a->delRef(mptr); if(a->getRef(mptr)==0) { delete mptr; } mptr=src.mptr; if(mptr!=NULL) { a->addRef(mptr); } return *this; } T& operator *() { return *mptr; } T* operator ->() { return mptr; } operator void *()//使用类型转换如果需要类型转换 { if(a->getRef(mptr)>0) { return mptr; } return NULL; }private: static maps_ptr *a; T *mptr; friend class Cweak<T>;};template<typename T>maps_ptr* smart_ptr<T>::a=maps_ptr::getptr();template <typename T>class Cweak{public: friend class smart_ptr<T>; Cweak(T *p=NULL):mptr(p){}; Cweak(const smart_ptr<T> &src) { //mptr=&*src; mptr=src.mptr; } Cweak& operator =(const smart_ptr<T> &src) { //mptr=&*src; mptr=src.mptr; return *this; } smart_ptr<T> lock() { return smart_ptr<T>(Cweak<T>(mptr)); }private: T *mptr;};class A{ public: A(){cout<<"A"<<endl;} ~A(){cout<<"~A"<<endl;} void func() { cout<<"hellowold"<<endl; }};int main(){ smart_ptr<A> ptr1(new A()); // smart_ptr<char>ptr2((char*)p); Cweak<A>ptr3(ptr1); smart_ptr<A> ptr=ptr3.lock(); if(ptr!=NULL) { cout<<"fdsafdsfsdfsdfsdf"<<endl; } return 0;}
阅读全文
0 0
- 智能指正和强弱指针的实现
- C++智能指针的设计和实现
- 智能指针的实现和原理
- C++智能指针的设计和实现
- 智能指针的简单剖析和实现
- 智能指针的理解 和 简单实现
- RAII和智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的简单实现
- 智能指针的类实现
- C++ 智能指针的实现
- 智能指针的部分实现
- 智能指针的一种实现
- c++智能指针的实现
- 多线程一定快吗
- Quartz分布式任务(二)
- 005. Spring 自动装配
- 每段时间Android开发10个知道(初级系列)-170622
- poj 3176 Cow Bowling
- 智能指正和强弱指针的实现
- 返回顶部
- secureCRT 日志保存并记录每条记录的时间
- java面试题之JDK和JRE的区别是什么?
- UnicodeWarning
- 33 款主宰 2017 iOS 开发的开源库
- 38. Count and Say
- 离散数学 p313 所有顶点都是偶度数的连通图有欧拉回路 证明
- ie8及其以下版本兼容性问题之文本省略