fork(4) 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::weak_ptr<Foo> weak_this = shared_from_this();
  11.  
  12. return [weak_this]() {
  13. auto that = weak_this.lock();
  14. if (!that) {
  15. std::cout << "The object is already dead" << std::endl;
  16. return;
  17. }
  18.  
  19. std::cout << that->name << std::endl;
  20. };
  21. }
  22.  
  23. std::string name;
  24. };
  25.  
  26. int main() {
  27. std::function<void()> f;
  28.  
  29. {
  30. auto foo = std::make_shared<Foo>("OK");
  31. f = foo->GetPrinter();
  32. }
  33.  
  34. auto foo = std::make_shared<Foo>("WRONG");
  35.  
  36. f();
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
The object is already dead