智能指针(还缺少scoped_ptr的模拟实现)

来源:互联网 发布:微信抓取朋友圈数据库 编辑:程序博客网 时间:2024/05/22 09:04
以下四个智能指针都是boost库中的1.auto_ptr  管理权转移,带有缺陷的设计。尽量不要使用它2.scoped_ptr 防拷贝,高效简洁。不需要拷贝/赋值,尽量使用它3.shared_ptr 共享(引用计数)管理、支持赋值/拷贝。缺陷:循环使用(针对循环使用有weak_ptr).4.weak_ptr辅助shared_ptr解决循环引用,不增加引用计数。

下面是关于auto_ptr的模拟实现

template<class T>class AutoPtr{public:    AutoPtr(T* ptr)        :_ptr(ptr)    {}    AutoPtr(AutoPtr<T>& ap)        :_ptr(ap._ptr)    {        ap._ptr = NULL;    }    ~AutoPtr()    {        if (_ptr)        {            cout << _ptr << endl;            delete[] _ptr;            _ptr = NULL;        }    }    T& operator *()    {        return *_ptr;    }    T* operator ->()    {        return _ptr;    }protected:    T* _ptr;};struct AA{    int _a1;    int _a2;};int main(){    AutoPtr<int> ap1(new int(10));    *ap1 = 20;    AutoPtr<AA> ap2(new AA);    (*ap2)._a1 = 10;    (*ap2)._a2 = 20;    ap2->_a1 = 30;    ap2->_a2 = 40;    system("pause");    return 0;}

下面是关于shared_ptr的模拟实现

emplate<class T>class SharedPtr{public:    SharedPtr(T* ptr)        :_ptr(ptr)        , _countRef(new int(1))    {}    SharedPtr(const SharedPtr<T>& sp)        :_ptr(sp._ptr)        , _countRef(sp._countRef)    {        ++(*_countRef);    }    SharedPtr<T>& operator=(const SharedPtr<T>& sp)    {        if (_ptr != sp._countRef)        {            Release();            _ptr = sp._ptr;            _countRef = sp._countRef;            ++(*_countRef);        }        return *this;    }    ~SharedPtr()    {        Release();    }    T& operator *()    {        return *_ptr;    }    T* operator ->()    {        return _ptr;    }    inline void Release()    {        if (--(*_countRef) == 0)        {            cout << _ptr << endl;            delete _ptr;            delete _countRef;        }    }    int UseCount()    {        return *_countRef;    }protected:    T* _ptr;    int* _countRef;//引用计数};
原创粉丝点击