templete<typename T>
class Shared_ptr{
public:
Shared_ptr(T* ptr = NULL):_ptr(ptr), _pcount(new int(1)){}
Shared_ptr(const Shared_str& s):_ptr(s._ptr), _pcount(s._pcount){
++(*_pcount);
}
Shared_ptr<T>& operator=(const Shared_ptr& s){
if(this != &s){
if(--(*(this->_pconut)) == 0){
delete this->_ptr;
delete this->_pcount;
}
_ptr = s._ptr;
_pcount = s._pcount;
*_pcount += 1;
}
return *this;
}
T& operator*(){
return *(this->_ptr);
}
T* operator->(){
return this->_ptr;
}
~Shared_ptr(){
*_pcount -= 1;
if(*_pcount == 0){
delete _ptr;
delete _pcount;
_ptr = NULL;
_pcount = NULL;
}
}
private:
T* _ptr;
int* _pcount;
};
手写智能指针 shared_ptr
最新推荐文章于 2024-07-08 22:12:26 发布