fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. class Story
  8. {
  9. int n;
  10. public:
  11. Story(int n): n(n) { cout << "story #" << n << " created" << endl; }
  12. ~Story() { cout << "story #" << n << " destroyed" << endl; }
  13. void print() { cout << "story #" << n << " reporting" << endl; }
  14. };
  15.  
  16. int main()
  17. {
  18. vector<shared_ptr<Story>> main_list;
  19. vector<weak_ptr<Story>> aux_list;
  20.  
  21. cout << "creating and adding to owning list" << endl;
  22. main_list.emplace_back(make_shared<Story>(1));
  23. main_list.emplace_back(make_shared<Story>(2));
  24. cout << "copying to non-owning list" << endl;
  25. aux_list.push_back(main_list[0]);
  26. aux_list.push_back(main_list[1]);
  27. cout << "removing #2" << endl;
  28. main_list.resize(1);
  29. for (auto& weakptr : aux_list)
  30. {
  31. if (auto strongptr = weakptr.lock())
  32. strongptr->print();
  33. else
  34. cout << "(deleted entry)" << endl;
  35. }
  36. cout << "cleaning non-owning list" << endl;
  37. aux_list.erase(
  38. remove_if(begin(aux_list), end(aux_list), [](auto wp) { return wp.expired(); }),
  39. end(aux_list));
  40. for (auto& weakptr : aux_list)
  41. {
  42. if (auto strongptr = weakptr.lock())
  43. strongptr->print();
  44. else
  45. cout << "(cannot happen)" << endl;
  46. }
  47. cout << "done" << endl;
  48. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
creating and adding to owning list
story #1 created
story #2 created
copying to non-owning list
removing #2
story #2 destroyed
story #1 reporting
(deleted entry)
cleaning non-owning list
story #1 reporting
done
story #1 destroyed