#include<iostream>
using namespace std;
template<class T>
class SmartPtr
{
T* ptr;
public:
SmartPtr(T* p=nullptr):ptr(p)
{
cout <<"Constructor"<<endl;
}
//Copy Constructor
SmartPtr(const SmartPtr& a)
{
cout <<"Copy Constructor"<<endl;
ptr = new T;
*ptr = *a.ptr;
}
//Copy assignment
SmartPtr& operator=(const SmartPtr& a )
{
cout <<"Operator = "<<endl;
if(&a==this)
return *this;
delete ptr;
ptr = new T;
*ptr = *a.ptr;
return *this;
}
//Move Constructor
SmartPtr(const SmartPtr&& a):ptr(a.ptr)
{
a.ptr = nullptr;
}
//Move assignment
SmartPtr& operator=(const SmartPtr&& a)
{
if(&a == this)
return *this;
delete ptr;
// Transfer ownership of a.ptr to ptr
ptr = a.ptr;
a.ptr = nullptr;
}
~SmartPtr()
{
cout <<"Destructor "<<endl;
delete ptr;
}
T& operator *(){return *ptr;}
T* operator ->(){return ptr;}
};
int main() {
// your code goes here
SmartPtr<int> sp (new int(5));
cout <<"sp value : "<<*sp<<endl;
SmartPtr<int> sp1 = sp;
cout <<"sp1 value : "<<*sp1<<endl;
SmartPtr<int> sp2(new int (10));
cout <<"sp2 value before : "<<*sp2<<endl;
sp2 = sp;
cout <<"sp2 value after : "<<*sp2<<endl;
return 0;
}