码迷,mamicode.com
首页 > 编程语言 > 详细

C++支持继承关系的智能指针

时间:2015-07-18 17:02:22      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

class RefCounted
{
protected:
    RefCounted(){ m_ref_count = 0; }
    virtual ~RefCounted(){}
public:
    void incRef() { ++m_ref_count; }
    void desRef()
    {
        if (--m_ref_count == 0) { delete this; }
    }
private:
    int m_ref_count;
};


template<typename T>
class RefPtr
{
public:
    RefPtr(){ m_ptr = 0; }

    template<typename U>
    RefPtr(U* ptr)
    {
        m_ptr = ptr;
        if (m_ptr) { m_ptr->incRef(); }
    }

    template<typename U>
    RefPtr(const RefPtr<U>& ptr)
    {
        m_ptr = ptr.getRefPtr();
        if (m_ptr) { m_ptr->incRef(); }
    }

    ~RefPtr()
    {
        if (m_ptr)
        {
            m_ptr->desRef();
            m_ptr = 0;
        }
    }

    template<typename U>
    RefPtr<T>& operator=(U* ptr)
    {
        if (m_ptr != ptr)
        {
            if (m_ptr) { m_ptr->desRef(); }
            m_ptr = ptr;
            if (m_ptr) { m_ptr->incRef(); }
        }
        return *this;
    }

    template<typename U>
    RefPtr<T>& operator=(const RefPtr<U>& ptr)
    {
        if (m_ptr != ptr.getRefPtr())
        {
            if (m_ptr) { m_ptr->desRef(); }
            m_ptr = ptr.getRefPtr();
            if (m_ptr) { m_ptr->incRef(); }
        }
        return *this;
    }

    T* operator->() const { return m_ptr; }
    T& operator*() const { return *m_ptr; }
    operator bool() const { return (m_ptr != 0); }
    T* getRefPtr() const { return m_ptr; }

private:
    T* m_ptr;
};

template<typename T, typename U>
bool operator==(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.getRefPtr() == b.getRefPtr()); }
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, const U* b) { return (a.getRefPtr() == b); }
template<typename T, typename U>
bool operator==(const U* a, const RefPtr<T>& b) { return (a == b.getRefPtr()); }

template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.getRefPtr() != b.getRefPtr()); }
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, const U* b) { return (a.getRefPtr() != b); }
template<typename T, typename U>
bool operator!=(const U* a, const RefPtr<T>& b) { return (a != b.getRefPtr()); }

 

C++支持继承关系的智能指针

标签:

原文地址:http://www.cnblogs.com/liusijian/p/4657105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!