#include <iostream>
using namespace std;
template<class T>
class SmartPtr{
public:
explicit SmartPtr():ptr(nullptr), count(new int(0)){}
explicit SmartPtr(T* p):ptr(p), count(new int(0)){
*count = 1;
}
~SmartPtr(){
--(*count);
if(*count == 0){
delete(count);
delete(ptr);
count = nullptr;
ptr = nullptr;
}
}
//拷贝构造
SmartPtr(const SmartPtr<T> &other){
count = other.count;
ptr = other.ptr;
++(*count);
}
SmartPtr& operator= (const SmartPtr<T> &other){
count = other.count;
ptr = other.ptr;
++(*count);
return (*this);
}
T& operator*(){
return *ptr;
}
T* operator->(){
return ptr;
}
void swap(SmartPtr<T> other){
std::swap(*this, other);
}
void use_count(){
cout<<(*count)<<endl;
}
private:
T *ptr;
int* count{};
};
int main() {
SmartPtr<int> ptr1(new int(1));
ptr1.use_count();
SmartPtr<int> ptr2(ptr1);
ptr1.use_count();
ptr2.use_count();
SmartPtr<int> ptr3 = ptr2;
ptr1.use_count();
ptr2.use_count();
ptr3.use_count();
return 0;
}