template <typename T>
class myshared_ptr{
public:
myshared_ptr(T* ptr = nullptr):_ptr(ptr){
count = new int(0);
if(ptr != nullptr){
*count = 1;
}
cout<<"myshared_ptr(T* ptr = nullptr)"<<endl;
}
~myshared_ptr(){
if(--*count == 0){
delete _ptr;
_ptr = nullptr;
delete count;
count = nullptr;
}
cout<<"~myshared_ptr()"<<endl;
}
myshared_ptr(myshared_ptr const & another){
_ptr = another._ptr;
count = another.count;
(*count)++;
cout<<"myshared_ptr(myshared_ptr const & another)"<<endl;
}
myshared_ptr & operator=(myshared_ptr const & another){
if(this != &another){
if(*--count == 0){
delete _ptr;
delete count;
}
_ptr = another._ptr;
count = another.count;
(*another.count)++;
cout<<" myshared_ptr & operator=(myshared_ptr const & another)"<<endl;
}
return *this;
}
T operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
int use_count(){
return *count;
}
private:
int *count;
T *_ptr;
};
智能指针shared_ptr自实现
最新推荐文章于 2024-05-25 13:58:15 发布