#include #include #include using namespace std; struct Link { int value; //shared_ptr other; weak_ptr other; Link(int v) { value = v; } ~Link() { cout << "~Link\n"; } }; ostream & operator<<(ostream & os, const Link &s) { // os << "Link " << &s << " -> " << s.other.get() << " v=" << s.value << endl; os << "Link " << &s << " -> " << s.other.lock().get() << " v=" << s.value << endl; return os; } int main() { int x; shared_ptr p1(new Link(100)); shared_ptr p2(new Link(200)); cout << *p1; cout << *p2; p1->other = p2; p2->other = p1; cout << *p1; cout << *p2; cout << p1.use_count() << endl; cout << p2.use_count() << endl; weak_ptr wp; { auto sp = make_shared(123); wp = sp; cout << wp.lock().get(); cout << " " << wp.use_count(); cout << " " << *(wp.lock()) << endl; } cout << " " << wp.use_count() << endl; if (wp.expired()) cout << "expired\n"; if (wp.lock() == nullptr) cout << "sp nullptr\n"; return 0; }