fork download
  1. #include <iostream>
  2.  
  3. struct copy_me
  4. {
  5. int i;
  6.  
  7. copy_me(int i) : i(i) { std::cout << "ctor" << std::endl; }
  8. copy_me(const copy_me& r) : i(r.i) { std::cout << "copy ctor" << std::endl; }
  9. copy_me(copy_me&& r) : i(r.i) { std::cout << "move ctor" << std::endl; }
  10. ~copy_me() { std::cout << "dtor" << std::endl; }
  11.  
  12. copy_me& operator =(const copy_me& r) { i = r.i; std::cout << "copy assgn" << std::endl; return *this; }
  13. copy_me& operator =(copy_me&& r) { i = r.i; std::cout << "move assgn" << std::endl; return *this; }
  14. };
  15.  
  16. copy_me copy_elision()
  17. {
  18. copy_me test(10);
  19.  
  20. int abc = std::rand();
  21.  
  22. while (abc < 10)
  23. abc += 1 + abc * abc;
  24.  
  25. std::cout << "abc: " << abc << std::endl;
  26.  
  27. return test;
  28. }
  29.  
  30. copy_me maybe_move()
  31. {
  32. int abc = std::rand();
  33.  
  34. while (abc < 10)
  35. abc += 1 + abc * abc;
  36.  
  37. std::cout << "abc: " << abc << std::endl;
  38.  
  39. copy_me test(abc);
  40.  
  41. std::cout << abc * abc << std::endl;
  42.  
  43. return test;
  44. }
  45.  
  46. copy_me move()
  47. {
  48. copy_me test(10);
  49.  
  50. int abc = std::rand();
  51.  
  52. while (abc < 10)
  53. abc += 1 + abc * abc;
  54.  
  55. std::cout << "abc: " << abc << std::endl;
  56.  
  57. return std::move(test);
  58. }
  59.  
  60. int main()
  61. {
  62. std::cout << "== Init: Elision ==" << std::endl;
  63. copy_me ce = copy_elision();
  64.  
  65. std::cout << "== Assignment: Elision ==" << std::endl;
  66. ce = copy_elision();
  67.  
  68. std::cout << "== Init: Move? ==" << std::endl;
  69. copy_me mamo = maybe_move();
  70.  
  71. std::cout << "== Assignment: Move? ==" << std::endl;
  72. mamo = maybe_move();
  73.  
  74. std::cout << "== Init: Move ==" << std::endl;
  75. copy_me mo = move();
  76.  
  77. std::cout << "== Assignment: Move ==" << std::endl;
  78. mo = move();
  79.  
  80. std::cout << "== End ==" << std::endl;
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0s 2932KB
stdin
Standard input is empty
stdout
== Init: Elision ==
ctor
abc: 1804289383
== Assignment: Elision ==
ctor
abc: 846930886
move assgn
dtor
== Init: Move? ==
abc: 1681692777
ctor
-738927855
== Assignment: Move? ==
abc: 1714636915
ctor
-1772952663
move assgn
dtor
== Init: Move ==
ctor
abc: 1957747793
move ctor
dtor
== Assignment: Move ==
ctor
abc: 424238335
move ctor
dtor
move assgn
dtor
== End ==
dtor
dtor
dtor