fork download
  1.  
  2. #include <iostream>
  3. #include <cassert>
  4. #include <vector>
  5.  
  6. class MyClass
  7. {
  8. public:
  9. explicit MyClass(
  10. int theA,
  11. int theB
  12. ) : myA(theA),
  13. myB(theB)
  14. {
  15. return;
  16. };
  17.  
  18. MyClass(
  19. MyClass && theOther
  20. ) : myA(std::move(theOther.myA)),
  21. myB(std::move(theOther.myB))
  22. {
  23. return;
  24. }
  25.  
  26. MyClass & operator=(
  27. MyClass && theOther
  28. ) {
  29. assert(this != &theOther);
  30.  
  31. myA = std::move(theOther.myA);
  32. myB = std::move(theOther.myB);
  33. }
  34.  
  35. private:
  36. // Not default-constructible.
  37. explicit MyClass();
  38.  
  39. // Enforce move-semantics.
  40. MyClass(const MyClass & theOther);
  41. MyClass & operator=(const MyClass & theOther);
  42.  
  43. public:
  44. int myA;
  45. int myB;
  46. };
  47.  
  48. int main(int argc, char * argv[])
  49. {
  50. std::vector<MyClass> v1;
  51. std::vector<MyClass> v2;
  52.  
  53. v1.push_back(MyClass(1, 2));
  54. v1.push_back(MyClass(2, 3));
  55. v1.push_back(MyClass(2, 4));
  56.  
  57. // Works.
  58. for(auto i = 0u; i < v1.size(); i++)
  59. if(v1[i].myA == 2)
  60. v2.push_back(std::move(v1[i]));
  61.  
  62.  
  63. // Does not work: Calls copy-constructor.
  64. for(auto i = v1.begin(); i != v1.end(); i++)
  65. if(i->myA == 2)
  66. v2.push_back(std::move(*i));
  67.  
  68.  
  69. // list1 may not be used any longer!
  70.  
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0s 3056KB
stdin
Standard input is empty
stdout
Standard output is empty