Skip to content

Instantly share code, notes, and snippets.

@bolry
Last active January 8, 2017 22:14
Show Gist options
  • Save bolry/e401ea122799a3b04e7b62c4882a354f to your computer and use it in GitHub Desktop.
Save bolry/e401ea122799a3b04e7b62c4882a354f to your computer and use it in GitHub Desktop.
A complete reference-counted object cache
shared_ptr<widget> get_widget(int id) {
static map<int, weak_ptr<widget>> cache;
static mutex m;
lock_guard<mutex> hold(m);
auto sp = cache[id].lock();
if (!sp) cache[id] = sp = load_widget(id);
return sp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment