fork download
  1. #include <functional>
  2. #include <iostream>
  3.  
  4. class Foo final
  5. {
  6. public:
  7. Foo() { std::cout << "Default constructor" << std::endl; }
  8. Foo(const Foo&) { std::cout << "Copy constructor" << std::endl; }
  9. Foo(Foo&&) noexcept { std::cout << "Move constructor" << std::endl; }
  10.  
  11. Foo& operator=(const Foo&)
  12. {
  13. std::cout << "Copy assignment" << std::endl;
  14.  
  15. return *this;
  16. }
  17.  
  18. Foo& operator=(Foo&&) noexcept
  19. {
  20. std::cout << "Move assignment" << std::endl;
  21.  
  22. return *this;
  23. }
  24.  
  25. std::function<void()> f() const noexcept
  26. {
  27. return [*this]{ g(); };
  28. }
  29.  
  30. ~Foo() noexcept
  31. {
  32. std::cout << "Destructor" << std::endl;
  33. }
  34.  
  35. private:
  36. void g() const noexcept
  37. {
  38. std::cout << "Hello, World! :-)" << std::endl;
  39. }
  40. };
  41.  
  42. void f(std::function<void()> cb) noexcept
  43. {
  44. if (cb)
  45. {
  46. cb();
  47. }
  48. }
  49.  
  50. int main()
  51. {
  52. std::function<void()> cb;
  53.  
  54. std::cout << '1' << std::endl;
  55. {
  56. Foo foo;
  57. std::cout << '2' << std::endl;
  58. cb = foo.f();
  59. std::cout << '3' << std::endl;
  60. }
  61.  
  62. std::cout << '4' << std::endl;
  63. f(std::move(cb));
  64. std::cout << '5' << std::endl;
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
1
Default constructor
2
Copy constructor
Copy constructor
Destructor
3
Destructor
4
Hello, World! :-)
Destructor
5