首页 > 代码库 > 实现一个简单的shared_ptr

实现一个简单的shared_ptr

template <typename T>
class shared_ptr
{
public:
    explicit shared_ptr (T *ptr): mPtr(ptr), cnt(new int(1)){}
    shared_ptr(const shared_ptr& rhs): mPtr(rhs.mPtr), cnt(rhs.cnt){ ++*cnt; }
    shared_ptr& operator = (const shared_ptr&);
    ~shared_ptr();

    T& operator *() { return *mPtr; }
    T* operator -> () { return mPtr; }
    void reset(T* ptr);
    T* get() const { return mPtr; }
private:
    T* mPtr;
    int *cnt;
};
template <typename T>
shared_ptr<T>& shared_ptr<T>::operator=(const shared_ptr& rhs)
{
    if (this == &rhs)
        return *this;
    --*cnt;
    if (*cnt == 0)
    {
        delete mPtr;
        delete cnt;
    }
    cnt = rhs.cnt;
    ++*cnt;
    mPtr = rhs.mPtr;
    return *this;
}
template <typename T>
void shared_ptr<T>::reset(T* ptr)
{
    --*cnt;
    if (*cnt == 0)
    {
        delete mPtr;
        delete cnt;
    }
    cnt = new int(1);
    mPtr = ptr;
}
template <typename T>
shared_ptr<T>::~shared_ptr()
{
    --*cnt;
    if (*cnt == 0)
    {
        delete mPtr;
        delete cnt;
    }
}

 

实现一个简单的shared_ptr