fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <utility>
  4. #include <vector>
  5.  
  6. class Foo final
  7. {
  8. public:
  9. Foo() : i_{}
  10. {
  11. std::cout << "Default Constructor" << std::endl;
  12. }
  13.  
  14. explicit Foo(const int i) : i_{i}
  15. {
  16. std::cout << "Parameterized Constructor: " << i_ << std::endl;
  17. }
  18.  
  19. Foo(const Foo& other) : i_{other.i_}
  20. {
  21. std::cout << "Copy Constructor: " << i_ << std::endl;
  22. }
  23.  
  24. Foo(Foo&& other) noexcept : i_{std::exchange(other.i_, 0)}
  25. {
  26. std::cout << "Move Constructor: " << i_ << "; other.i_: " << other.i_
  27. << std::endl;
  28. }
  29.  
  30. Foo& operator=(const Foo& other)
  31. {
  32. i_ = other.i_;
  33.  
  34. std::cout << "Copy assignment operator: " << i_ << std::endl;
  35.  
  36. return *this;
  37. }
  38.  
  39. Foo& operator=(Foo&& other) noexcept
  40. {
  41. std::swap(i_, other.i_);
  42.  
  43. std::cout << "Move assignment operator: " << i_ << "; other.i_: "
  44. << other.i_ << std::endl;
  45.  
  46. return *this;
  47. }
  48.  
  49. const int& i() const noexcept
  50. {
  51. std::cout << "Getter" << std::endl;
  52.  
  53. return i_;
  54. }
  55.  
  56. int& i()
  57. {
  58. std::cout << "Setter" << std::endl;
  59.  
  60. return i_;
  61. }
  62.  
  63. ~Foo() noexcept
  64. {
  65. std::cout << "Destructor" << std::endl;
  66. }
  67.  
  68. private:
  69. int i_;
  70. };
  71.  
  72. int main()
  73. {
  74. std::cout << '1' << std::endl;
  75. std::vector<Foo> foos{ Foo{1994} };
  76.  
  77. std::cout << '2' << std::endl;
  78. std::for_each(foos.begin(), foos.end(),
  79. [](Foo& foo)
  80. {
  81. foo.i() /= 2;
  82. });
  83.  
  84. std::cout << '3' << std::endl;
  85. for (const Foo& foo : foos)
  86. {
  87. std::cout << foo.i() << ' ';
  88. }
  89. std::cout << std::endl;
  90.  
  91. return 0;
  92. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
1
Parameterized Constructor: 1994
Copy Constructor: 1994
Destructor
2
Setter
3
Getter
997 
Destructor