仿智能指针

来源:互联网 发布:淘宝客服话术模板 编辑:程序博客网 时间:2024/06/05 14:10
#pragma once
#ifndef _REF_PTR_h
#define _REF_PTR_h


class CRefObject
{
public:
    CRefObject()
    {
        m_nRefCount = 0;
    }
    virtual ~CRefObject()
    {
    
    }


    int GetRefCount() const
    {
        return m_nRefCount;
    }


    int AddRefCount()
    {
        return ++m_nRefCount;
    }


    int SubRefCount()
    {
        return --m_nRefCount;
    }


    void ResetRefCount()
    {
        m_nRefCount = 0;
    }


private:
    int    m_nRefCount;
};


//T 必须继承自 CRefObject
template<typename T>
class CRefPtr
{
public:
    T* operator->() const
    {
        return m_ptrObj;
    }


    T& operator()() const
    {
        assert(m_ptrObj != NULL);
        return *m_ptrObj;
    }


    T& operator*() const
    {
        assert(m_ptrObj != NULL);
        return *m_ptrObj;
    }


    T* GetPtr() const
    {
        return m_ptrObj;
    }


    bool IsNull() const
    {
        return m_ptrObj == NULL;
    }


    explicit CRefPtr(T* p = NULL)
    {
        m_ptrObj = p;
        if(p != NULL)
        {
            p->AddRefCount();
        }
    }


    CRefPtr(const CRefPtr& ref)
    {
        m_ptrObj = ref.m_ptrObj;
        if(m_ptrObj != NULL)
        {
            m_ptrObj->AddRefCount();
        }
    }


    ~CRefPtr()
    {
        try
        {
            if(m_ptrObj != NULL && m_ptrObj->SubRefCount() == 0)
            {
                delete m_ptrObj;
            }
        }
        catch (...)
        {
        }


    }


    CRefPtr& operator = (const CRefPtr& ref)
    {
        if(this != &ref)
        {
            if(m_ptrObj != NULL
                && m_ptrObj->SubRefCount() == 0)
            {
                delete m_ptrObj;
            }


             //lint -e{1555}
            m_ptrObj = ref.m_ptrObj;
            //lint +e1555


            if(m_ptrObj != NULL)
            {
                m_ptrObj->AddRefCount();
            }
        }


        return *this;
    }


    bool operator == (const CRefPtr& ref) const
    {
        return m_ptrObj == ref.m_ptrObj;
    }


private:
    T* m_ptrObj;
};


#endif


example:

class testobj  public CRefObject
{

}


CRefPtr<testobj  > m_test;

m_test= CRefPtr<testobj  > (new testobj () );




2 0
原创粉丝点击