自己实现一个shared_ptr
,比较简洁,只是有个样子罢了。
template<typename T>
class shared_ptr
{
private:
T* _ptr;
int* _pcnt;
public:
shared_ptr(T* p)
: _ptr(p),
_pcnt(new int(1))
{}
//拷贝构造函数
shared_ptr(const shared_ptr& s) : _ptr(s._ptr), _pcnt(s._pcnt)
{
(*_pcnt)++;
}
//重载operator=
shared_ptr<T>& operator=(const shared_ptr& s){
if(this != &s){
if(--(*(this->_pcnt)) == 0){ //当前指针托管的对象引用计数变为0
delete _ptr;
_ptr = nullptr;
delete _pcnt;
_pcnt = nullptr;
}
_ptr = s._ptr;
_pcnt = s._pcnt;
(*_pcnt)++; //s托管的对象引用计数累加
}
return *this;
}
//重载operator* *p返回指向的对象
T& operator*(){
return *(this->_ptr);
}
//重载operator-> 返回指向T的指针
T* operator->(){
return this->_ptr;
}
//析构函数
~shared_ptr(){
if(_ptr && --(*_pcnt) == 0){
delete _ptr;
_ptr = nullptr;
delete _pcnt;
_pcnt = nullptr;
}
}
};