smartPtr指针的实现

编写一个智能指针类。智能指针是一种数据类型,一般用模板实现,模拟指针行为的同时还提供自动来及回收机制。它会自动记录SmartPointer<T*>对象的引用计数,一旦T类型对象的引用计数为零,就会释放该对象。

解法:

智能指针跟普通指针一样,但它借由自动化内存管理保证了安全性,避免了诸如悬挂指针、内存泄漏和分配失败等问题。

智能指针必须为给定对象的所有引用维护单一引用计数。

实现代码:

 

template<class T>
class SmartPointer
{
public:
    SmartPointer(T* ptr)
    {
        ref=ptr;
        ref_count=(unsigned*)malloc(sizeof(unsigned));
        *ref_count=1;
    }
    
    
    SmartPonter(SmartPointer &rhs)
    {
        ref=rhs.ref;
        ref_count=rhs.ref_count;
        ++(*ref_count);
    }
        
    SmartPointer& operator=(SmartPointer& rhs)
    {
        if(*this==rhs)
            return *this;
        if(ref_count>0)
            remove();
        ref=rhs.ref;
        ref_count=obj.ref_count;
        ++(*ref_count);
        return *this;
    }

    ~SmartPointer()
    {
        remove();
    }
    
    T getValue()
    {
        return *ref;
    }
    
protected:
    void remove()
    {
        --(*ref_count);
        if(*ref_count==0)
        {
            delete ref;
            free(ref_count);
            ref=NULL;
            ref_count=NULL;
        }
    }
    T *ref;
    unsigned *ref_count;
};

 

posted @ 2015-03-29 23:32  Jessica程序猿  阅读(566)  评论(0编辑  收藏  举报