#include #include #include #include #include using namespace std; class Demo { public: Demo() { cout << "default Demo ctor: " << this << endl; } Demo(const Demo&) { cout << "copy Demo ctor: " << this << endl; } ~Demo() { cout << "Demo dtor: " << this << endl; } }; ostream& operator<<(ostream& out, const Demo&) { out << "Demo object"; return out; } template ostream& operator<<(ostream& out, const shared_ptr& obj); int main() { shared_ptr sp1; shared_ptr sp2(nullptr); shared_ptr sp3(new string("carrot")); shared_ptr sp4(make_shared("potato")); shared_ptr sp5(sp3); cout << "sp1: " << sp1 << endl; cout << "sp2: " << sp2 << endl; cout << "sp3: " << sp3 << endl; cout << "sp4: " << sp4 << endl; cout << "sp5: " << sp5 << endl << endl; cout << "sp1 = sp4;" << endl; sp1 = sp4; cout << "sp1: " << sp1 << endl; cout << "sp4: " << sp4 << endl << endl; cout << "sp2 = sp3;" << endl; sp2 = sp3; cout << "sp2: " << sp2 << endl; cout << "sp3: " << sp3 << endl << endl; cout << "sp1.reset();" << endl; sp1.reset(); cout << "sp1: " << sp1 << endl << endl; shared_ptr sp6(nullptr); // create an "empty" shared pointer shared_ptr sp7(new Demo); // calls Demo default ctor shared_ptr sp8(new Demo(*sp7)); // calls Demo copy ctor shared_ptr sp9(make_shared()); // calls Demo default ctor shared_ptr sp10(sp7); // calls shared_ptr copy ctor cout << "sp6: " << sp6 << endl; cout << "sp7: " << sp7 << endl; cout << "sp8: " << sp8 << endl; cout << "sp9: " << sp9 << endl; cout << "sp10:" << sp10 << endl << endl; cout << "sp6 = move(sp7);" << endl; sp6 = move(sp7); cout << "sp6: " << sp6 << endl; cout << "sp7: " << sp7 << endl << endl; cout << "sp6.reset();" << endl; sp6.reset(); cout << "sp6: " << sp6 << endl; cout << "sp10: " << sp10 << endl << endl; cout << "sp10.reset();" << endl; sp10.reset(); cout << "sp6: " << sp6 << endl; cout << "sp7: " << sp7 << endl; cout << "sp8: " << sp8 << endl; cout << "sp9: " << sp9 << endl; cout << "sp10:" << sp10 << endl << endl; cout << "That's all folks" << endl; } template ostream& operator<<(ostream& out, const shared_ptr& obj) { if (obj.get()) out << setw(10) << obj.get() << " " << setw(8) << *obj << " " << obj.use_count(); else out << setw(10) << obj.get(); return out; }