Favorite 10-Liner

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s