fork download
  1. #include <iostream>
  2.  
  3. struct A
  4. {
  5. A( int ii ) : i(ii) { std::cout << "constructor i == " << i << '\n' ; }
  6.  
  7. A( const A& that ) : i(that.i)
  8. { std::cout << "copy constructor i == " << i << '\n' ; }
  9.  
  10. ~A() { std::cout << "destructor i == " << i << '\n' ; }
  11.  
  12. A( A& that ) : i(that.i)
  13. { std::cout << "move constructor i == " << i << '\n' ; }
  14.  
  15. A& operator= ( const A& that )
  16. { i = that.i ; std::cout << "copy assignment i == " << i << '\n' ; return *this ; }
  17.  
  18. A& operator= ( A&& that )
  19. { i = that.i ; std::cout << "move assignment i == " << i << '\n' ; return *this ; }
  20.  
  21. int i ;
  22. };
  23.  
  24. A operator+ ( const A& a, const A& b )
  25. {
  26. A temp( a.i + b.i ) ; // RVO applies, constructing 'temp'
  27. return temp ; // and then copying temp is elided
  28. // the function directly constructs the return value, 'temp' is elided
  29. }
  30.  
  31. int main()
  32. {
  33. A a(6) ; // constructor i == 6
  34. A b(8) ; // constructor i == 8
  35. A c(0) ; // constructor i == 0
  36. std::cout << "------------------------------\n" ;
  37.  
  38. c = a+b ; // call operator+(a,b), RVO applies
  39. // step one:
  40. // construct anonymous temporary 'in place' - constructor i == 14
  41. // no copy or move constructor is involved
  42.  
  43. // step two:
  44. // assign the anonymous temporary returned by operator+ to c
  45. // move assignment i == 14
  46.  
  47. // step three:
  48. // destroy the anonymous temporary returned by operator+
  49. // destructor i == 14
  50. std::cout << "------------------------------\n" ;
  51.  
  52. a.i = 100 ;
  53. b.i = 56 ;
  54.  
  55. A d = a+b ; // call operator+(a,b), RVO applies
  56. // this function returns a prvalue ("pure rvalue")
  57. // a prvalue need not be associated with any object, it can be elided
  58. // therefore, construct d 'in place'
  59. // construct d - constructor i == 156
  60. // no copy or move constructor is involved
  61. std::cout << "------------------------------\n" ;
  62.  
  63. std::cout << "press enter to destroy 'a', 'b', 'c' and 'd' and then quit\n" ;
  64. std::cin.get() ;
  65.  
  66. // destroy d - destructor i == 156
  67. // destroy c - destructor i == 14
  68. // destroy b - destructor i == 56
  69. // destroy a - destructor i == 100
  70. }
  71.  
Success #stdin #stdout 0s 3344KB
stdin
stdout
constructor i == 6
constructor i == 8
constructor i == 0
------------------------------
constructor i == 14
move assignment i == 14
destructor i == 14
------------------------------
constructor i == 156
------------------------------
press enter to destroy 'a', 'b', 'c' and 'd' and then quit
destructor i == 156
destructor i == 14
destructor i == 56
destructor i == 100