fork 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 = make_shared<MyClass>(); // since C++11
  15. cout << "Use count: " << sp1.use_count() << endl;
  16.  
  17. weak_ptr<MyClass> wp = sp1;
  18. cout << "Use count: " << sp1.use_count() << endl; // Only shared_ptr counts, weak_ptr does not
  19. cout << "Use count: " << wp.use_count() << endl;
  20.  
  21. {
  22. cout << "Entered inner block." << endl;
  23. shared_ptr<MyClass> sp2 = wp.lock();
  24. cout << "Use count: " << sp1.use_count() << endl;
  25.  
  26. if(sp2)
  27. cout << "Lock acquired." << endl;
  28. cout << "Leaving inner block." << endl;
  29. }
  30. cout << "Left inner block." << endl;
  31. cout << "Use count: " << sp1.use_count() << endl;
  32.  
  33. cout << "About to delete the last shared pointer." << endl;
  34. sp1.reset();
  35. cout << "Deleted the last shared pointer." << endl;
  36.  
  37. shared_ptr<MyClass> sp3 = wp.lock();
  38. if(!sp3)
  39. cout << "Shared object does not exists anymore." << endl;
  40.  
  41. if(wp.expired()) // Not thread safe solution.
  42. cout << "Shared object does not exists anymore." << endl;
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
MyClass ctor runned.
Use count: 1
Use count: 1
Use count: 1
Entered inner block.
Use count: 2
Lock acquired.
Leaving inner block.
Left inner block.
Use count: 1
About to delete the last shared pointer.
MyClass dtor runned.
Deleted the last shared pointer.
Shared object does not exists anymore.
Shared object does not exists anymore.