智能指针的定义和使用
来源: 钟英杰/
华南师范大学
691
2
0
2017-03-29

定义一般基类


class stCountObject
{
private:

    int m_iCount;

public:

    stCountObject():m_iCount(0) {}

    virtual ~stCountObject() {}

    void AddRef(){ ++m_iCount;}//add reference

    void RemoveRef()//minu reference
    {
        --m_iCount;
        if(m_iCount <= 0)
        {
            delete this;
        }
    }

    int GetCount() //Get a reference
    {
        return m_iCount;
    }

};



定义智能指针


template<class T>
class stCountedPtr
{

private:

    T *m_pCountObj;

public:
    stCountedPtr():m_pCountObj(0){}
    stCountedPtr(T* pObject)
    {
        m_pCountObj = pObject;

        if(m_pCountObj)
        {
            m_pCountObj->AddRef();
        }
    }

    stCountedPtr(const stCountedPtr <T> &pPtr)
    {
        m_pCountObj = pPtr;

        if(m_pCountObj)
        {
            m_pCountObj->AddRef();
        }
    }

    ~stCountedPtr()
    {
        if(m_pCountObj != 0)
        {
            int iCount = m_pCountObj->GetCount();

            m_pCountObj->RemoveRef();
            if(iCount ==1)
            {
                m_pCountObj = 0;
            }
        }
    }

    stCountedPtr<T> &operator = (const stCountedPtr<T> &pPtr)
    {
        if(m_pCountObj != pPtr.m_pCountObj)
        {
            if(m_pCountObj != 0)
            {
                int iCount = m_pCountObj->GetCount();
                m_pCountObj->RemoveRef();

                if(iCount == 1)
                {
                    m_pCountObj = 0;
                }
            }

            m_pCountObj = pPtr.m_pCountObj;
            if(m_pCountObj != 0)
            {
                m_pCountObj->AddRef();
            }
        }

        return this;
    }
    /*
    T& Operator *()const
    {
        return *m_pCountObj;
    }

    T *Oprator->()const
    {
        return m_pCountObj();
    }

    Operat T*()const
    {
        return m_pCountObj;
    }
    */

};

class stCLine :public stCountObject
{
public:

    stCLine(){}
    ~stCLine(){}
    void DrawLine()
    {
        printf("DrawLine");
    }
};

调用实例


typedef stCountedPtr<stCLine*>  stLinePtr;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    stLinePtr line;
    line->Draw();

    //line->Draw();

    return a.exec();
}
内存泄露是很平常的问题,困扰着无数的程序员,如何有效的防止内存泄露智能指针无疑是一个很好的方法。智能指针一个用到模版(template ),另一个是设计模式中的代理模式,对对象的有效管理。



登录用户可以查看和发表评论, 请前往  登录 或  注册
SCHOLAT.com 学者网
免责声明 | 关于我们 | 联系我们
联系我们: