fork download
  1. #include <iostream>
  2. #include <initializer_list>
  3.  
  4. struct list
  5. {
  6. list() { std::cout << "default constructor\n" ; }
  7.  
  8. list( std::initializer_list<int> il )
  9. {
  10. std::cout << "constructor from initializer_list\n" ;
  11. for( int v : il ) push_back(v) ;
  12. }
  13.  
  14. list( const list& that )
  15. {
  16. std::cout << "copy constructor\n" ;
  17. for( node* n = that.first ; n ; n = n->next ) push_back( n->value ) ;
  18. }
  19.  
  20. list( list&& that ) noexcept
  21. {
  22. std::cout << "move constructor\n" ;
  23. first = that.first ; that.first = nullptr ;
  24. last = that.last ; that.last = nullptr ;
  25. }
  26.  
  27. ~list()
  28. {
  29. std::cout << "destructor\n" ;
  30. while(first) pop_back() ;
  31. }
  32.  
  33. list& operator=( const list& that ) ; // TODO
  34. list& operator=( list&& that ) noexcept ; // TODO
  35.  
  36. void push_back( int v )
  37. {
  38. if(last) { last->next = new node( v, last ) ; last = last->next ; }
  39. else first = last = new node(v) ;
  40. }
  41.  
  42. void pop_back()
  43. {
  44. if( last != first ) { last = last->prev ; delete last->next ; last->next = nullptr ; }
  45. if( last && last == first ) { delete last ; last = first = nullptr ; }
  46. }
  47.  
  48. struct node
  49. {
  50. node( int v ) : value(v) {}
  51. node( int v, node* p ) : value(v), prev(p) {}
  52.  
  53. int value ;
  54. node* next = nullptr ;
  55. node* prev = nullptr ;
  56. };
  57.  
  58. node* first = nullptr ;
  59. node* last = nullptr ;
  60. };
  61.  
  62. list foo()
  63. {
  64. std::cout << "in function foo\n" ;
  65. return { 1, 2, 3, 4, 5 } ;
  66. }
  67.  
  68. list bar()
  69. {
  70. std::cout << "in function bar\n" ;
  71. list temp ;
  72. for( int i = 1 ; i < 6 ; ++i ) temp.push_back(i) ;
  73. return temp ;
  74. }
  75.  
  76. int main()
  77. {
  78. {
  79. list a = foo() ;
  80. std::cout << "back in main\n" ;
  81. for( auto n = a.first ; n ; n = n->next ) std::cout << n->value << ' ' ;
  82. std::cout << '\n' ;
  83. }
  84.  
  85. std::cout << "----------------------------\n" ;
  86.  
  87. {
  88. list b = bar() ;
  89. std::cout << "back in main\n" ;
  90. for( auto n = b.first ; n ; n = n->next ) std::cout << n->value << ' ' ;
  91. std::cout << '\n' ;
  92. }
  93. }
  94.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
in function foo
constructor from initializer_list
back in main
1 2 3 4 5 
destructor
----------------------------
in function bar
default constructor
back in main
1 2 3 4 5 
destructor