fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. int main()
  5. {
  6. // create a sharable allocation
  7. std::shared_ptr<int> var1 = std::make_shared<int>(102);
  8. std::cout << "*var1 = " << *var1 << '\n';
  9.  
  10. // create a weak pointer to our shared pointer. we can't do much with
  11. // it until we convert it to a shared pointer
  12. std::weak_ptr<int> var2 = var1;
  13.  
  14. try
  15. { // try shared pointer conversion
  16. std::shared_ptr<int> varx(var2);
  17. std::cout << "*var2 = " << *varx << '\n';
  18. }
  19. catch(std::exception const& ex)
  20. {
  21. std::cout << "Exception: " << ex.what() << '\n';
  22. }
  23.  
  24. // release original shared pointer. this will release
  25. // the only hard reference to the data, and all weak
  26. // pointers become invalid.
  27. var1.reset();
  28.  
  29. try
  30. { // try that again, but this time it should not work
  31. std::shared_ptr<int> varx(var2);
  32. std::cout << "*var2 = " << *varx << '\n';
  33. }
  34. catch(std::exception const& ex)
  35. {
  36. std::cout << "Exception: " << ex.what() << '\n';
  37. }
  38. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
*var1 = 102
*var2 = 102
Exception: bad_weak_ptr