Listing 3
#include <memory> #include <iostream> using std::tr1::shared_ptr; using std::tr1::weak_ptr; using std::tr1::bad_weak_ptr; using std::cout; static void construct(weak_ptr<int> wp) { // construct shared_ptr object from weak_ptr object cout << " using constructor, "; try { // wrap construction shared_ptr<int> sp(wp); cout << "succeeded\n"; } catch(const bad_weak_ptr& ex) { // something's wrong cout << "caught " << ex.what() << '\n'; } } static void lock(weak_ptr<int> wp) { // initialize shared_ptr object from wp.lock() cout << " using lock, "; shared_ptr<int> sp = wp.lock(); if (sp) cout << "got ownership\n"; else cout << "got empty object\n"; } int main() { // demonstrate weak_ptr/shared_ptr conversions shared_ptr<int> sp(new int); weak_ptr<int> wp(sp); cout << "Valid resource, use count is " << wp.use_count() << ":\n"; construct(wp); lock(wp); sp.reset(); cout << "Expired resource, use count is " << wp.use_count() << ":\n"; construct(wp); lock(wp); return 0; }