//SmartPtr.h
//Wang Bin 2006-06-07
#ifndef SMART_PTR_H
#define SMART_PTR_H
template <typename _T>
class SmartPtr{
public:
SmartPtr(_T* p=0):m_Ptr(p),m_pCount(p?new unsigned int(1):0)
{
}
SmartPtr(SmartPtr& p):m_Ptr(p.m_Ptr),m_pCount(p.get()?p.addref():0)
{
}
SmartPtr& operator = (SmartPtr& p)
{
if(m_Ptr)
release();
m_Ptr=p.get();
m_pCount=p.addref();
return *this;
}
SmartPtr& operator = (_T* p)
{
if(m_Ptr)
release();
if(p)
{
m_pCount=new unsigned int(1);
}
m_Ptr=p;
return *this;
}
operator _T*() const
{
return get();
}
_T* operator ->() const
{
return get();
}
_T operator *() const throw()
{
return *get();
}
bool operator ==(_T* p) const
{
return m_Ptr==p;
}
bool operator !=(_T* p) const
{
return m_Ptr!=p;
}
virtual void release()
{
if(m_Ptr)
{
(*m_pCount)--;
if(!*m_pCount)
{
delete m_Ptr;
delete m_pCount;
m_Ptr=0;
m_pCount=0;
}
}
}
virtual ~SmartPtr()
{
release();
}
protected:
_T* get() const
{
return m_Ptr;
}
unsigned int* addref()
{
if(m_Ptr)
(*m_pCount)++;
return m_pCount;
}
_T *m_Ptr;
unsigned int *m_pCount;
};
template <typename _T>
class SmartArray:public SmartPtr<_T>{
public:
SmartArray(_T* p=0):SmartPtr<_T>(p)
{
}
SmartArray(SmartArray& p):SmartPtr<_T>(p)
{
}
SmartArray& operator = (SmartArray& p)
{
SmartPtr<_T>::operator =(p);
return *this;
}
SmartArray& operator = (_T* p)
{
SmartPtr<_T>::operator =(p);
return *this;
}
virtual void release()
{
if(m_Ptr)
{
(*m_pCount)--;
if(!*m_pCount)
{
delete[] m_Ptr;
delete m_pCount;
m_Ptr=0;
m_pCount=0;
}
}
}
virtual ~SmartArray()
{
if(*m_pCount==1)
{
delete[] m_Ptr;
delete m_pCount;
m_Ptr=0;
m_pCount=0;
}
}
};
typedef SmartPtr<int> intPtr;
typedef SmartArray<int> intArrayPtr;
#endif //SMART_PTR_H