fork download
  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4.  
  5. class A
  6. {
  7. int *ptr;
  8. public:
  9. A(int a)
  10. {
  11. ptr = new int(a);
  12. std::cout<<"Constructor : "<<*ptr<<endl;
  13. }
  14. A(const A& a)
  15. {
  16. std::cout<<"Copy Constructor : "<<*(a.ptr)<<endl;
  17. ptr = new int(*(a.ptr));
  18. *ptr = *a.ptr;
  19. }
  20. A& operator=(const A& a)
  21. {
  22. std::cout<<"Copy Assignment "<<*a.ptr<<endl;
  23. if(this != &a)
  24. {
  25. delete ptr;
  26. ptr = new int(*a.ptr);
  27. }
  28.  
  29. return *this;
  30. }
  31. A(A&& a):ptr(a.ptr)
  32. {
  33. std::cout<<"Move Constructor : "<<*a.ptr<<endl;
  34. a.ptr = nullptr;
  35. }
  36. A& operator=(A && a)
  37. {
  38. std::cout<<"Move Assignment : "<<*a.ptr<<endl;
  39. if(&a != this)
  40. {
  41. ptr = a.ptr;
  42. a.ptr = nullptr;
  43. }
  44. return *this;
  45. }
  46. ~A()
  47. {
  48. std::cout<<"Destructor : ";
  49. if(ptr)
  50. {
  51. std::cout<<*ptr<<endl;
  52. delete ptr;
  53. }
  54. }
  55. };
  56.  
  57. int main()
  58. {
  59. vector<A> vec;
  60. vec.push_back(A(1));
  61. A a1(2);
  62. vec.push_back(a1);
  63. A a2(3);
  64. vec.push_back(std::move(a2));
  65. a2 = a1;
  66. a1 = A(4);
  67. }
Success #stdin #stdout 0.01s 5564KB
stdin
Standard input is empty
stdout
Constructor : 1
Move Constructor : 1
Destructor : Constructor : 2
Copy Constructor : 2
Copy Constructor : 1
Destructor : 1
Constructor : 3
Move Constructor : 3
Copy Constructor : 1
Copy Constructor : 2
Destructor : 1
Destructor : 2
Copy Assignment 2
Constructor : 4
Move Assignment : 4
Destructor : Destructor : 2
Destructor : 4
Destructor : 1
Destructor : 2
Destructor : 3