shared_ptr< widget > get_widget( int id ) { static map< int, weak_ptr< widget > > cache; static mutex m; lock_guard< mutex > holder( m ); auto sp = cache[ id ].lock(); if ( !sp ) cache[ id ] = sp = load_widget( id ); return sp; } // credit to Herb Sutter @ Going Native 2013
Isn’t this awesome?
No?
Well, let’s see…
- Is this thread-safe?
- What’s the lifetime of the objects in the cache?
- What happens if you ask for an object not in the cache?
And so… Isn’t this awesome?
P.S. the other 3 lines:
Widget &instance() { static Widget w; return w; } // credit to Herb Sutter @ Going Native 2013
