#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
using namespace std;
class Story
{
int n;
public:
Story(int n): n(n) { cout << "story #" << n << " created" << endl; }
~Story() { cout << "story #" << n << " destroyed" << endl; }
void print() { cout << "story #" << n << " reporting" << endl; }
};
int main()
{
vector<shared_ptr<Story>> main_list;
vector<weak_ptr<Story>> aux_list;
cout << "creating and adding to owning list" << endl;
main_list.emplace_back(make_shared<Story>(1));
main_list.emplace_back(make_shared<Story>(2));
cout << "copying to non-owning list" << endl;
aux_list.push_back(main_list[0]);
aux_list.push_back(main_list[1]);
cout << "removing #2" << endl;
main_list.resize(1);
for (auto& weakptr : aux_list)
{
if (auto strongptr = weakptr.lock())
strongptr->print();
else
cout << "(deleted entry)" << endl;
}
cout << "cleaning non-owning list" << endl;
aux_list.erase(
remove_if(begin(aux_list), end(aux_list), [](auto wp) { return wp.expired(); }),
end(aux_list));
for (auto& weakptr : aux_list)
{
if (auto strongptr = weakptr.lock())
strongptr->print();
else
cout << "(cannot happen)" << endl;
}
cout << "done" << endl;
}