fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. class Story
  7. {
  8. int n;
  9. public:
  10. Story(int n): n(n) { cout << "story #" << n << " created" << endl; }
  11. ~Story() { cout << "story #" << n << " destroyed" << endl; }
  12. };
  13.  
  14. int main()
  15. {
  16. vector<shared_ptr<Story>> list1, list2;
  17.  
  18. cout << "creating #1 and adding to first list" << endl;
  19. list1.emplace_back(make_shared<Story>(1));
  20. cout << "copying #1 to second list" << endl;
  21. list2.push_back(list1[0]);
  22. cout << "creating #2" << endl;
  23. auto story2 = make_shared<Story>(2);
  24. cout << "adding #2 to the second list" << endl;
  25. list2.push_back(story2);
  26. cout << "removing first ptr to story #2" << endl;
  27. story2 = nullptr;
  28. cout << "removing second ptr to story #2, now it will be destroyed" << endl;
  29. list2.resize(1);
  30. cout << "clearing first list" << endl;
  31. list1.clear();
  32. cout << "clearing second list, now story #1 will be destroyed" << endl;
  33. list2.clear();
  34. cout << "done" << endl;
  35. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
creating #1 and adding to first list
story #1 created
copying #1 to second list
creating #2
story #2 created
adding #2 to the second list
removing first ptr to story #2
removing second ptr to story #2, now it will be destroyed
story #2 destroyed
clearing first list
clearing second list, now story #1 will be destroyed
story #1 destroyed
done