template<typename T>
class My_shared_ptr{
T* ptr;
int* count;
public:
My_shared_ptr(T*);
My_shared_ptr(const My_shared_ptr&);
~My_shared_ptr();
My_shared_ptr& operator=(const My_shared_ptr&);
T* operator->();
T& operator*();
};
template<typename T>
My_shared_ptr<T>::My_shared_ptr(T* t){//构造函数
if(t){
ptr = t;
count = new(int);
*count=1;
}else { //避免空间的浪费
ptr = NULL;
count = NULL;
}
}
template<typename T>
My_shared_ptr<T>::My_shared_ptr(const My_shared_ptr& sp){ //拷贝构造函数
if(sp.ptr){
ptr = sp.ptr;
count = sp.count;
(*count)++;
}else{
ptr = NULL;
count = NULL;
}
}
template<typename T>
My_shared_ptr<T>::~My_shared_ptr(){
if(--(*count)==0){
delete count;
delete ptr;
}
}
template<typename T>
My_shared_ptr<T>& My_shared_ptr<T>::operator=(const My_shared_ptr& sp){
if(ptr){
if(--(*count)==0){
delete count;
delete ptr;
ptr = NULL;
count = NULL;
}
}
ptr = sp.ptr;
count = sp.count;
if(sp) (*count)++;
}
template<typename T>
T& My_shared_ptr<T>::operator*(){
if(ptr){
return *ptr;
}
return NULL;
}
template<typename T>
T* My_shared_ptr<T>::operator->(){
return ptr;
}
(实现智能指针)
于 2023-02-24 15:07:03 首次发布