fork(2) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4.  
  5. class Foo : public std::enable_shared_from_this<Foo> {
  6. public:
  7. Foo(const std::string& i_name) : name(i_name) {}
  8.  
  9. std::function<void()> GetPrinter() {
  10. std::shared_ptr<Foo> that = shared_from_this();
  11.  
  12. return [that]() {
  13. std::cout << that->name << std::endl;
  14. };
  15. }
  16.  
  17. std::string name;
  18. };
  19.  
  20. int main() {
  21. std::function<void()> f;
  22.  
  23. {
  24. auto foo = std::make_shared<Foo>("OK");
  25. f = foo->GetPrinter();
  26. }
  27.  
  28. auto foo = std::make_shared<Foo>("WRONG");
  29.  
  30. f();
  31.  
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
OK