fork(1) download
  1. #include<vector>
  2. #include<iostream>
  3. class X
  4. {
  5. std::vector<double> data;
  6. public:
  7. // Constructor1
  8. X():
  9. data(100000) // lots of data
  10. {}
  11.  
  12. // Constructor2
  13. X(X const& other): // copy constructor
  14. data(other.data) // duplicate all that data
  15. {}
  16.  
  17. // Constructor3
  18. X(X&& other): // move constructor
  19. data(std::move(other.data)) // move the data: no copies
  20. {std::cout<<"\nMove constructor";}
  21.  
  22. X& operator=(X const& other) // copy-assignment
  23. {
  24. std::cout<<"\nCopy assignment";
  25. data=other.data; // copy all the data
  26. return *this;
  27. }
  28.  
  29. X& operator=(X && other) // move-assignment
  30. {
  31. std::cout<<"\nMove assignment";
  32. data=std::move(other.data); // move the data: no copies
  33. return *this;
  34. }
  35.  
  36. };
  37.  
  38. X make_x() // build an X with some data
  39. {
  40. X myNewObject; // Constructor1 gets called here
  41. // fill data..
  42. return myNewObject; // Constructor3 gets called here
  43. }
  44.  
  45.  
  46. int main()
  47. {
  48. X x1;
  49. //X x2(x1); // copy
  50. //X x3(std::move(x1)); // move: x1 no longer has any data
  51.  
  52. x1=make_x(); // return value is an rvalue, so move rather than copy
  53. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
Move assignment