#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;
}
智能指正和强弱指针的实现
最新推荐文章于 2021-12-27 18:00:00 发布