fork download
  1. #include<iostream>
  2. using namespace std;
  3. template<class T>
  4. class SmartPtr
  5. {
  6. T* ptr;
  7. public:
  8. SmartPtr(T* p=nullptr):ptr(p)
  9. {
  10. cout <<"Constructor"<<endl;
  11. }
  12. //Copy Constructor
  13. SmartPtr(const SmartPtr& a)
  14. {
  15. cout <<"Copy Constructor"<<endl;
  16. ptr = new T;
  17. *ptr = *a.ptr;
  18. }
  19. //Copy assignment
  20. SmartPtr& operator=(const SmartPtr& a )
  21. {
  22. cout <<"Operator = "<<endl;
  23. if(&a==this)
  24. return *this;
  25.  
  26. delete ptr;
  27. ptr = new T;
  28. *ptr = *a.ptr;
  29. return *this;
  30. }
  31.  
  32. //Move Constructor
  33. SmartPtr(const SmartPtr&& a):ptr(a.ptr)
  34. {
  35. a.ptr = nullptr;
  36. }
  37.  
  38. //Move assignment
  39. SmartPtr& operator=(const SmartPtr&& a)
  40. {
  41. if(&a == this)
  42. return *this;
  43. delete ptr;
  44. // Transfer ownership of a.ptr to ptr
  45. ptr = a.ptr;
  46. a.ptr = nullptr;
  47.  
  48. }
  49. ~SmartPtr()
  50. {
  51. cout <<"Destructor "<<endl;
  52. delete ptr;
  53. }
  54.  
  55. T& operator *(){return *ptr;}
  56. T* operator ->(){return ptr;}
  57.  
  58. };
  59.  
  60.  
  61.  
  62. int main() {
  63. // your code goes here
  64. SmartPtr<int> sp (new int(5));
  65. cout <<"sp value : "<<*sp<<endl;
  66. SmartPtr<int> sp1 = sp;
  67. cout <<"sp1 value : "<<*sp1<<endl;
  68. SmartPtr<int> sp2(new int (10));
  69. cout <<"sp2 value before : "<<*sp2<<endl;
  70. sp2 = sp;
  71. cout <<"sp2 value after : "<<*sp2<<endl;
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 5664KB
stdin
Standard input is empty
stdout
Constructor
sp value : 5
Copy Constructor
sp1 value : 5
Constructor
sp2 value before : 10
Operator = 
sp2 value after : 5
Destructor 
Destructor 
Destructor