shared_ptr get_widget( int id ) { static map< int, weak_ptr > cache; static mutex m; lock_guard hold(m); auto sp = cache[id].lock(); // cache[id] returns a weak_ptr. lock() returns the shared_ptr if( !sp ) cache[id] = sp = load_widget(id); return sp; }