带引用计数的智能指针
#define DbgPrint(...) printf(__VA_ARGS__)
#define DbgEnter() {DbgPrint("+%s/n",__FUNCSIG__);DbgPrint("+pointer_=0x%x,refcount_=0x%x,*refcount_=0x%x/n",pointer_,refcount_,refcount_==0?0:*refcount_);}
#define DbgLeave() {DbgPrint("+pointer_=0x%x,refcount_=0x%x,*refcount_=0x%x/n",pointer_,refcount_,refcount_==0?0:*refcount_);DbgPrint("-%s/n",__FUNCSIG__);}
//带引用计数的智能指针
template<typename T>
class XSharedPointer
{
public:
XSharedPointer();
XSharedPointer(T* t);
XSharedPointer(const XSharedPointer<T>& t);
virtual ~XSharedPointer();
T& operator*();
T* operator->();
XSharedPointer<T>& operator=(const XSharedPointer<T>& t);
XSharedPointer<T>& operator=(const T* t);
void clear();
protected:
private:
T* pointer_;
unsigned int* refcount_;
};
template<typename T>
XSharedPointer<T>::XSharedPointer():refcount_(0),pointer_(0)
{
DbgEnter();
pointer_=0;
refcount_=0;
DbgLeave();
}
template<typename T>
XSharedPointer<T>::XSharedPointer(T* t):refcount_(0),pointer_(0)
{
DbgEnter();
pointer_=t;
if (t!=0)
{
refcount_=new unsigned int(1);
}
else
{
refcount_=0;
}
DbgLeave();
}
template<typename T>
XSharedPointer<T>::XSharedPointer(const XSharedPointer<T>& t):refcount_(0),pointer_(0)
{
DbgEnter();
pointer_=t.pointer_;
refcount_=t.refcount_;
if (refcount_!=0)
{
(*refcount_)++;
}
DbgLeave();
}
template<typename T>
XSharedPointer<T>::~XSharedPointer()
{
DbgEnter();
//引用计数-1;若==1则删除指针
if (refcount_!=0&&(*refcount_)--==1)
{
delete pointer_;
delete refcount_;
pointer_=0;
refcount_=0;
}
DbgLeave();
}
template<typename T>
T& XSharedPointer<T>::operator *()
{
DbgEnter();
DbgLeave();
return *pointer_;
}
template<typename T>
T* XSharedPointer<T>::operator ->()
{
DbgEnter();
DbgLeave();
return pointer_;
}
template<typename T>
XSharedPointer<T>& XSharedPointer<T>::operator=(const XSharedPointer<T>& t)
{
DbgEnter();
if (&t==this)
{
return *this;
}
if (refcount_!=0&&(*refcount_)--==1)
{
delete pointer_;
delete refcount_;
pointer_=0;
refcount_=0;
}
refcount_=t.refcount_;
if (refcount_!=0)
{
(*refcount_)++;
}
pointer_=t.pointer_;
DbgLeave();
return *this;
}
template<typename T>
XSharedPointer<T>& XSharedPointer<T>::operator =(const T* t)
{
DbgEnter();
if (refcount_!=0&&(*refcount_)--==1)
{
delete pointer_;
delete refcount_;
pointer_=0;
refcount_=0;
}
refcount_=new int(1);
pointer_=t;
DbgLeave();
return *this;
}
/* 清除共享指针 */
template<typename T>
void XSharedPointer<T>::clear()
{
DbgEnter();
if (refcount_!=0&&(*refcount_)--==1)
{
delete pointer_;
delete refcount_;
}
pointer_=0;
refcount_=0;
DbgLeave();
}