智能指针类(ScopedPointer和SharedPointer)
当ScopedPoniter对象销毁时,会自动释放所指堆空间对象。
当SharedPointer对象销毁时,会自动将引用计数减1,只有当引用计数为0时才会释放堆空间对象。
- Pointer类 接口类
- ScopedPointer类 不可拷贝
- SharedPointer类 带引用计数
template <typename T>
class Pointer: public Object
{
protected:
T* m_pointer;
public:
Pointer(T* p = NULL) : m_pointer (p)
{ }
T* operator ->()
{ return m_pointer; }
T& operator * ()
{ return *m_pointer;}
bool isNull()
{ return (m_pointer == NULL); }
T* get() const
{ return m_pointer;}
virtual ~Pointer() = 0;
};
template <typename T>
Pointer<T>::~Pointer()
{ }
template<typename T>
class ScopedPointer : public Pointer<T>
{
private:
ScopedPointer(const ScopedPointer<T>&);
ScopedPointer<T>& operator = (const ScopedPointer<T>&);
void operator==( ScopedPointer const& ) const;
void operator!=( ScopedPointer const& ) const;
public:
ScopedPointer(T* p = NULL): Pointer<T>(p)
{}
void reset(T* p = NULL)
{
ScopedPointer<T>(p).swap(*this);
}
void swap(ScopedPointer & b)
{
T * tmp = b.m_pointer;
b.m_pointer = this->m_pointer;
this->m_pointer = tmp;
}
~ScopedPointer()
{
checked_delete<T>(this->m_pointer);
}
};
template<typename T>
class SharedPointer: public Pointer<T>
{
public:
SharedPointer(T* p=NULL): Pointer<T>(NULL),m_ref(NULL)
{
assign(p);
}
SharedPointer(const SharedPointer<T>& obj):Pointer<T>(NULL)
{
assign(obj);
}
SharedPointer<T>& operator = (const SharedPointer<T>& obj)
{
if(&obj != this)
{
clear();
assign(obj);
}
return *this;
}
void reset(T* p=NULL)
{
clear();
assign(p);
}
~SharedPointer()
{
clear();
}
int useCount() const
{
return (m_ref == NULL) ? 0 : *m_ref;
}
bool unique() const
{
return useCount() == 1;
}
private:
void assign(const SharedPointer<T>& obj)
{
this->m_ref = obj.m_ref;
this->m_pointer = obj.m_pointer;
if(this->m_ref)
{
(*this->m_ref)++;
}
}
void assign(T* p)
{
if(p)
{
this->m_ref = static_cast<int*>(new int(0));
if(this->m_ref)
{
this->m_pointer = p;
*(this->m_ref) = 1;
}
else
{
THROW_EXCEPTION(NoEnoughtMemoryException,"no memory to reate SharedPointer object ..");
}
}
}
void clear()
{
T* toDel =this->m_pointer;
int* ref = this->m_ref;
this->m_pointer = NULL;
this->m_ref = NULL;
if(ref)
{
(*ref)--;
if(*ref == 0)
{
delete ref;
checked_delete<T>(toDel);
}
}
}
protected:
int* m_ref;
};
template <typename T>
bool operator ==(const SharedPointer<T>& l,const SharedPointer<T>& r)
{
return (l.get() == r.get());
}
template <typename T>
bool operator !=(const SharedPointer<T>& l,const SharedPointer<T>& r)
{
return !(l == r);
}