Posts

Showing posts with the label weak references

Herb Sutter's favorite C++ 10-liner has a memory management bug

In a recently-posted video , Herb Sutter (a prominent C++ expert) describes his favorite C++ 10-liner as “a thread-safe 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; } This example is very interesting. Firstly, it manages to pull in reference counting, weak references and a mutex which are all very rare in modern programming. Secondly, it contains a memory leak that is difficult to fix in C++ because APIs are burdened with memory management details and this API is incapable of expressing deterministic cleanup because there is no facility for a widget's destructor to remove its entry in the map. Finally, the correct name for this data structure is a concurrent weak dictionary , specifically one with weak values. You'll find corre...