fork(2) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. using namespace std;
  5.  
  6. struct MyClass
  7. {
  8. MyClass() { cout << "MyClass ctor runned." << endl; }
  9. ~MyClass() { cout << "MyClass dtor runned." << endl; }
  10. };
  11.  
  12. int main()
  13. {
  14. shared_ptr<MyClass> sp1(new MyClass);
  15. cout << "Use count: " << sp1.use_count() << endl;
  16.  
  17. shared_ptr<MyClass> sp2 = sp1;
  18. cout << "Use count: " << sp1.use_count() << endl;
  19.  
  20. sp1.reset();
  21. cout << "Use count: " << sp2.use_count() << endl;
  22.  
  23. {
  24. cout << "Entered inner block." << endl;
  25. shared_ptr<MyClass> sp3 = sp2;
  26. cout << "Use count: " << sp2.use_count() << endl;
  27. cout << "Leaving inner block." << endl;
  28. }
  29. cout << "Left inner block." << endl;
  30. cout << "Use count: " << sp2.use_count() << endl;
  31.  
  32. cout << "About to delete the last shared pointer." << endl;
  33. sp2.reset();
  34. cout << "Deleted the last shared pointer." << endl;
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
MyClass ctor runned.
Use count: 1
Use count: 2
Use count: 1
Entered inner block.
Use count: 2
Leaving inner block.
Left inner block.
Use count: 1
About to delete the last shared pointer.
MyClass dtor runned.
Deleted the last shared pointer.