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