#include <iostream>
using namespace std;
template<class T>
class SmartPtr
{
public:
    SmartPtr(T *p){
        try
        {
            use_count = new int(1);
        }
        catch (...)
        {
            delete ptr;
            ptr = nullptr;
            use_count = nullptr;
            cout << "Allocate memory for use_count fails." << endl;
            exit(1);
        }
        cout << "Constructor is called!" << endl;
    }
    ~SmartPtr(){
        // 只在最后一个对象引用ptr时才释放内存
        if (--(*use_count) == 0)
        {
            delete ptr;
            delete use_count;
            ptr = nullptr;
            use_count = nullptr;
            cout << "Destructor is called!" << endl;
        }
    }
    SmartPtr(const SmartPtr<T> &orig){
        // 浅拷贝
        ptr = orig.ptr;
        use_count = orig.use_count;
        ++(*use_count);
        cout << "Copy constructor is called!" << endl;
    }
    SmartPtr<T>& operator=(const SmartPtr<T> &rhs){
        // 浅拷贝
        ++(*rhs.use_count);
        // 将左操作数对象的使用计数减1,若该对象的使用计数减至0,则删除该对象
        if (--(*use_count) == 0)
        {
            delete ptr;
            delete use_count;
            cout << "Left side object is deleted!" << endl;
        }
        ptr = rhs.ptr;
        use_count = rhs.use_count;
        cout << "Assignment operator overloaded is called!" << endl;
        return *this;
    }
private:
    T *ptr;
    // 将use_count声明成指针是为了方便对其的递增或递减操作
    int *use_count;
};


int main()
{
    // Test Constructor and Assignment Operator Overloaded
    SmartPtr<int> p1(new int(0));
    p1 = p1;
    // Test Copy Constructor
    SmartPtr<int> p2(p1);
    // Test Assignment Operator Overloaded
    SmartPtr<int> p3(new int(1));
    p3 = p1;
    cin.get();
    return 0;
}