C++智能指针简单实现

#ifndef SHARE_PTR_H
#define SHARE_PTR_H

template<typename T>
class CSharePtr
{
public:
    CSharePtr( T* ptr)
    {
        if(ptr)
        {
            m_pPtr = ptr;
            m_nRef = 1;
        }else
        {
            m_nRef = 0;
            m_pPtr = nullptr;
        }  
    }

    CSharePtr(const CSharePtr<T>& sptr)
    {
        m_nRef = sptr.m_nRef;
        m_pPtr = sptr.m_pPtr;
        m_nRef++;
    }

    CSharePtr<T>& operator=(const CSharePtr<T>& sptr)
    {
        if(this == &sptr)
        {
            return *this;
        }

        ReleasePtr();
        m_nRef = sptr.m_nRef;
        m_pPtr = sptr.m_pPtr;
        m_nRef++;

        return *this;
    }

    ~CSharePtr()
    {
        ReleasePtr();
    }

    T getValue()   const
    {
        return *m_pPtr;
    }

    T* operator->() const
    {
        return m_pPtr;
    }

private:
    void ReleasePtr()
    {
        if(--m_nRef == 0)
        {
            delete m_pPtr;
            m_pPtr = nullptr;
        }
    }

private:
    int m_nRef;
    T* m_pPtr;
};

#endif

测试:

class  A
{
    public:
    A()
    {
        cout<<"A()"<<endl;
    }

    ~A()
    {
        cout<<"~A()"<<endl;
    }

    void Func()
    {
        cout<< "func() is excuted!"<<endl;
    }
};
CSharePtr<A>  sp = CSharePtr<A>(new A());
sp->Func();

你可能感兴趣的:(C/C++,设计模式,c++,智能指针)