fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class X
  6. {
  7. public:
  8.  
  9. std::vector<double> data;
  10.  
  11. // Constructor1
  12. X():
  13. data(100000) // lots of data
  14. {
  15. cout << "X() called" << endl;
  16. }
  17.  
  18. // Constructor2
  19. X(X const& other) // copy constructor
  20. : data(other.data) // duplicate all that data
  21. {
  22. cout << "X(X const& other) called" << endl;
  23. }
  24.  
  25. // Constructor3
  26. X(X&& other): // move constructor
  27. data(std::move(other.data)) // move the data: no copies
  28. {
  29. cout << "X(X&& other) called" << endl;
  30. }
  31.  
  32. X& operator=(X const& other) // copy-assignment
  33. {
  34. cout << "X& operator=(X const& other) called" << endl;
  35. data=other.data; // copy all the data
  36. return *this;
  37. }
  38.  
  39. X& operator=(X && other) // move-assignment
  40. {
  41. cout << "X& operator=(X && other) called" << endl;
  42. data=std::move(other.data); // move the data: no copies
  43. return *this;
  44. }
  45. };
  46.  
  47. class X2
  48. {
  49. public:
  50.  
  51. std::vector<double> data;
  52.  
  53. // Constructor1
  54. X2()
  55. : data(100000) // lots of data
  56. {
  57. cout << "X2() called" << endl;
  58. }
  59.  
  60. // Constructor2
  61. X2(X const& other)
  62. : data(other.data)
  63. {
  64. cout << "X2(const X&) called" << endl;
  65. }
  66.  
  67. X2& operator=(X const& other) // copy-assignment
  68. {
  69. data=other.data; // copy all the data
  70. cout << "X2::operator =(const X&) called" << endl;
  71. return *this;
  72. }
  73. };
  74.  
  75. X make_x()
  76. {
  77. X myNewObject;
  78. myNewObject.data.push_back(22);
  79. return myNewObject;
  80. }
  81.  
  82.  
  83. int main()
  84. {
  85. X x = make_x(); // x1 has a move constructor
  86. X2 x2 = make_x(); // x2 hasn't a move constructor
  87. return 0;
  88. }
Success #stdin #stdout 0s 2900KB
stdin
Standard input is empty
stdout
X() called
X() called
X2(const X&) called