fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. struct Parent;
  8. struct Child
  9. {
  10. shared_ptr<Parent> ptr;
  11.  
  12. Child(shared_ptr<Parent> a) :
  13. ptr(a)
  14. {}
  15. };
  16.  
  17. struct Parent : public enable_shared_from_this<Parent>
  18. {
  19. Child myChild;
  20.  
  21. Parent() :
  22. myChild(shared_ptr<Parent>(this))
  23. {}
  24.  
  25.  
  26. shared_ptr<Parent> getptr()
  27. {
  28. return shared_from_this();
  29. }
  30. };
  31.  
  32.  
  33. shared_ptr<Parent> p(new Parent);
  34. cout << "UC of parent: " << p.use_count() << endl;
  35. cout << "UC of child ptr: " << p->myChild.ptr.use_count() << endl;
  36.  
  37. shared_ptr<Parent> p2(p);
  38. cout << "UC of parent: " << p2.use_count() << endl;
  39. cout << "UC of child ptr: " << p2->myChild.ptr.use_count() << endl;
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
UC of parent: 1
UC of child ptr: 1
UC of parent: 2
UC of child ptr: 1