c++ 實現一個簡單的shared_ptr

c++實現 shared_ptr 帶刪除器

template<class T>
void Delete(T *&t){
    if(t){
        delete t;
        t= nullptr;
    }

}

template<class T>
class SharedPtr{
private:
    int *count;
    T *_ptr;
    void (*callback)(T *&p);
public:
    explicit SharedPtr(T *ptr,void (*deleter)(T *&p)= Delete):count(new int(1)),_ptr(ptr){
        callback=deleter;
    };
    SharedPtr(const SharedPtr &sharedPtr):count(&(++*sharedPtr.count)),_ptr(sharedPtr._ptr){};
    T& operator*(){return *_ptr;} // 注意
    T* operator->(){return _ptr;} // 注意
    ~SharedPtr(){
        if(*count==0){
            callback(_ptr);
            delete count;
            count= nullptr;
        }
    }
    SharedPtr & operator=(const SharedPtr &sharedPtr){
        ++*sharedPtr.count;
        if(this->_ptr && --*this->count==0){
            callback(_ptr);
            delete count;
            count= nullptr;
        }
        _ptr=sharedPtr._ptr;
        count=sharedPtr.count;
        return *this;
    }

    int getRef(){return *count;}

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章