fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. using namespace std;
  5.  
  6. struct MyClass
  7. {
  8. shared_ptr<MyClass> next;
  9.  
  10. MyClass(shared_ptr<MyClass> next)
  11. {
  12. this->next = next;
  13. cout << "Constructor completed for a MyClass object." << endl;
  14. }
  15.  
  16. virtual ~MyClass()
  17. {
  18. cout << "Destructor completed for a MyClass object." << endl;
  19. }
  20. };
  21.  
  22. int main()
  23. {
  24. shared_ptr<MyClass> nullp;
  25. shared_ptr<MyClass> sp1(new MyClass(nullp));
  26. shared_ptr<MyClass> sp2(new MyClass(sp1));
  27.  
  28. {
  29. cout << "Entered inner block." << endl;
  30. shared_ptr<MyClass> sp3(new MyClass(sp2));
  31. sp1->next = sp3; // Create cyclic referencing
  32. cout << "sp3 use count: " << sp3.use_count() << endl;
  33. cout << "Leaving inner block." << endl;
  34. }
  35. cout << "Left inner block." << endl;
  36.  
  37. cout << "sp1 use count: " << sp1.use_count() << endl;
  38. cout << "sp2 use count: " << sp2.use_count() << endl;
  39. cout << "sp3 use count: " << sp1->next.use_count() << endl;
  40.  
  41. sp1.reset();
  42. sp2.reset();
  43.  
  44. cout << "Released sp1 and sp2, dtors still not executed." << endl;
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Constructor completed for a MyClass object.
Constructor completed for a MyClass object.
Entered inner block.
Constructor completed for a MyClass object.
sp3 use count: 2
Leaving inner block.
Left inner block.
sp1 use count: 2
sp2 use count: 2
sp3 use count: 1
Released sp1 and sp2, dtors still not executed.