c++ 实现一个简单的shared_ptr

2021-08-05  本文已影响0人  东京的雨不会淋湿首尔

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;}

};

上一篇下一篇

猜你喜欢

热点阅读