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;}
};
网友评论