You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.9 KiB
C

#if !defined(__MY_SMART_PTR_TEMPLATE_H__)
#define __MY_SMART_PTR_TEMPLATE_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//<2F>Լ<EFBFBD><D4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>ģ<EFBFBD><C4A3>
template<typename TYPE>
class RefPtr
{
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ա<EFBFBD><D4B1><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8>ȫ<EFBFBD><C8AB>Ϊprivate<74><65><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>ֱ<EFBFBD><D6B1>ʹ<EFBFBD>ø<EFBFBD><C3B8><EFBFBD>
template<typename TYPE> friend class Sptr;
RefPtr(TYPE *ptr):p(ptr), count(1) { }
~RefPtr() { delete p; }
TYPE *GetPtr(){return p;}
int count; //<2F><><EFBFBD>ü<EFBFBD><C3BC><EFBFBD>
TYPE *p; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>
};
template<typename TYPE>
class Sptr
{
public:
Sptr(TYPE *ptr):rp(new RefPtr<TYPE>(ptr)) { } //<2F><><EFBFBD><EFBFBD><ECBAAF>
Sptr(const Sptr &sp):rp(sp.rp) { ++rp->count; } //<2F><><EFBFBD>ƹ<EFBFBD><C6B9><EFBFBD><ECBAAF>
Sptr& operator=(const Sptr& rhs)
{ //<2F><><EFBFBD>ظ<EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
++rhs.rp->count; //<2F><><EFBFBD>Ƚ<EFBFBD><C8BD>Ҳ<EFBFBD><D2B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ü<EFBFBD><C3BC><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD><31>
if(--rp->count == 0) //Ȼ<><C8BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ü<EFBFBD><C3BC><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD><31><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD>Ը<EFBFBD>ֵ
delete rp;
rp = rhs.rp;
return *this;
}
~Sptr()
{
if(--rp->count == 0) //<2F><><EFBFBD><EFBFBD><EFBFBD>ü<EFBFBD><C3BC><EFBFBD><EFBFBD><EFBFBD>Ϊ0ʱ<30><CAB1>ɾ<EFBFBD><C9BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><EFBFBD>Ӷ<EFBFBD>ɾ<EFBFBD><C9BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
delete rp;
}
//<2F><><EFBFBD>ز<EFBFBD><D8B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><C4A3>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD>Ϊ
TYPE &operator*() { return *rp->p; }
TYPE *operator->() { return rp->p; }
const TYPE &operator*() const { return *rp->p; }
const TYPE *operator->() const { return rp->p; }
TYPE *GetPtr(){return rp->GetPtr();}//<2F><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>
bool IsNull()
{
if(rp->GetPtr())
return false;
else
return true;
}
private:
RefPtr<TYPE> *rp; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>
};
#endif//__MY_SMART_PTR_TEMPLATE_H__