实现一个智能指针
template <typename T>
class SmartPtr {
private:
T *ptr_;
size_t *count_;
public:
explicit SmartPtr(T *p = nullptr): ptr_(p), count_(new size_t){
if(p)
*count_ = 1;// count_ = new size_t(1)
else
*count_ = 0;
}
SmartPtr(const SmartPtr& smart_ptr){
if(this != smart_ptr){ // 避免自赋值
ptr_ = smart_ptr.ptr_;
count_ = smart_ptr.count_;
(*count_)++;
}
}
~SmartPtr(){
if(--(*count_) == 0){
delete ptr_;
delete count_;
}
}
SmartPtr& operate=(SmartPtr& smart_ptr){
if(this->ptr_ != smart_ptr.ptr_){
// 原来的指向 -1
if(this->ptr_){
if(--(*count_) == 0){
delete ptr_;
delete count_;
}
}
this->ptr_ = smart_ptr.ptr_;
this->count_ = smart_ptr.count_;
(*this->count_)++;
// 新指向的this +1
}
return *this;
}
T* operator->(){
assert(this->ptr_ == nullptr);
return *ptr_;
}
T& operate*(){
if(ptr_)
return ptr_;
}
}