64,637
社区成员
发帖
与我相关
我的任务
分享
template <class T>
class smart_ptr
{
private:
class ref_counter
{
public:
ref_counter(T* p){ count = 0; ptr = p; }
void addRef(){ count++; }
void release(){ count--; if(count <= 0) destroy(); }
T* getPtr() const{ return ptr; }
private:
~ref_counter(){ if(ptr) delete ptr; }
void destroy(){ delete this; }
int count;
T* ptr;
};
public:
smart_ptr(){ refcount = NULL; }
smart_ptr(T* p){ refcount = NULL; reset(p); }
smart_ptr(const smart_ptr& sp){ refcount = NULL; reset(sp.refcount); }
~smart_ptr(){ reset((ref_counter*)NULL); }
T* get(){ return (refcount==NULL) ? NULL : refcount->getPtr(); }
void reset(T* p)
{
if(p == NULL) reset((ref_counter*)NULL);
else reset(new ref_counter(p));
}
smart_ptr& operator = (const smart_ptr& sp){ reset(sp.refcount); return *this; }
smart_ptr& operator = (T* p){ reset(p); return *this; }
T* operator -> (){ return get(); }
operator T* () const { return get(); }
bool operator ! (){ return get()==NULL; }
bool operator == (const smart_ptr& sp){ return get()==sp.get(); }
bool operator != (const smart_ptr& sp){ return get()!=sp.get(); }
private:
void reset(ref_counter* rc)
{
if(rc != NULL) rc->addRef();
ref_counter* oldref = refcount;
refcount = rc;
if(oldref != NULL) oldref->release();
}
ref_counter* refcount;
};