fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. std::weak_ptr<int> gw;
  5.  
  6. void observe()
  7. {
  8. std::cout << "gw.use_count() == " << gw.use_count() << "; ";
  9. // we have to make a copy of shared pointer before usage:
  10. if (std::shared_ptr<int> spt = gw.lock()) {
  11. std::cout << "*spt == " << *spt << '\n';
  12. }
  13. else {
  14. std::cout << "gw is expired\n";
  15. }
  16. }
  17.  
  18. int main()
  19. {
  20. {
  21. auto sp = std::make_shared<int>(42);
  22. gw = sp;
  23.  
  24. observe();
  25. }
  26.  
  27. observe();
  28. }
Success #stdin #stdout 0.01s 5428KB
stdin
Standard input is empty
stdout
gw.use_count() == 1; *spt == 42
gw.use_count() == 0; gw is expired