fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. #define DBG(TEXT) do{cout << "( " << m_name << m_id << " " << #TEXT << " )" << endl;}while(0)
  8.  
  9. #define USE_MOVE_SEMANTICS
  10.  
  11. class Foo
  12. {
  13. string m_name;
  14. unsigned int m_id;
  15. public:
  16.  
  17. // constructor
  18. Foo(const char *name)
  19. : m_name(name)
  20. , m_id(0)
  21. {
  22. DBG(constructor);
  23. }
  24.  
  25. // destructor
  26. ~Foo()
  27. {
  28. DBG(destructor);
  29. }
  30.  
  31. // copy constructor
  32. Foo(const Foo &other)
  33. : m_name(other.m_name)
  34. , m_id(other.m_id + 1)
  35. {
  36. DBG(copy constructor);
  37. }
  38.  
  39. // copy assignment operator
  40. Foo &operator=(const Foo &other)
  41. {
  42. m_name = other.m_name;
  43. m_id = other.m_id + 1;
  44. DBG(copy assignment operator);
  45. return *this;
  46. }
  47.  
  48. #ifdef USE_MOVE_SEMANTICS
  49.  
  50. // move constructor
  51. Foo(Foo &&other)
  52. : m_name(other.m_name)
  53. , m_id(other.m_id + 1)
  54. {
  55. DBG(move constructor);
  56. }
  57.  
  58. // move assignment operator
  59. Foo &operator=(Foo &&other)
  60. {
  61. m_name = other.m_name;
  62. m_id = other.m_id + 1;
  63. DBG(move assignment operator);
  64. return *this;
  65. }
  66.  
  67. #endif // USE_MOVE_SEMANTICS
  68.  
  69. };
  70.  
  71. int main(void)
  72. {
  73. vector<Foo> vec;
  74. vec.reserve(1);
  75.  
  76. cout << "Foo a(\"A\");" << endl;
  77. Foo a("A");
  78.  
  79. cout << "vec.push_back(a);" << endl;
  80. vec.push_back(a); // No reallocation.
  81.  
  82. cout << "vec.push_back(Foo(\"B\"));" << endl;
  83. vec.push_back(Foo("B")); // Reallocate memory and move elements.
  84.  
  85. cout << "vec[0] = Foo(\"C\");" << endl;
  86. vec[0] = Foo("C");
  87.  
  88. cout << "return 0;" << endl;
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 3076KB
stdin
Standard input is empty
stdout
Foo a("A");
( A0 constructor )
vec.push_back(a);
( A1 copy constructor )
vec.push_back(Foo("B"));
( B0 constructor )
( B1 move constructor )
( A2 move constructor )
( A1 destructor )
( B0 destructor )
vec[0] = Foo("C");
( C0 constructor )
( C1 move assignment operator )
( C0 destructor )
return 0;
( A0 destructor )
( C1 destructor )
( B1 destructor )