title: What's the recommended way to use static map to cache data in C++
body: <p>I have a table store a key value like data, which will be frequently used but rarely update. So I would like to store necessary data in the memory, and only update it when the update coming.</p>
  
  <p>Here is the simple code show my current solution.</p>
  
  <p><em>kv.h</em></p>
  
  <pre><code>class kv
  {
  public:
      string query(string key);
      void update(string key, string value);
  };
  </code></pre>
  
  <p><em>kv.cpp</em></p>
  
  <pre><code>#include "kv.h"
  #include &lt;map&gt;
  #include &lt;mutex&gt;
  #include &lt;thread&gt;
  
  static map&lt;string, string&gt; s_cacheMap;
  static mutex mtx;
  
  string kv::query(string key)
  {
      unique_lock&lt;mutex&gt; lock(mtx);
      if (s_cacheMap.empty())
      {
          // load from db
      }
  
      auto it = s_cacheMap.find(key);
      if (it != s_cacheMap.end())
      {
          return (*it).second;
      }
  
      return "";
  };
  
  void kv::update(string key, string value)
  {
      unique_lock&lt;mutex&gt; lock(mtx);
      s_cacheMap.clear();
      // write key value into db
  };
  </code></pre>
  
  <p><em>Problem of this solution</em></p>
  
  <p>Those code will be part of the library in the iOS platform wrote by C++. The app might be killed by system or user at anytime. I could get notification when app exit, but I only have a very short time to clean up before user terminate the app. I couldn't guarantee those threads still running when application is terminating get correct result, but I'd like to make sure it doesn't crash.</p>
  
  <p>At the end of the application lifecycle, those two static variable will be destroyed. When those two static variable have been destroyed, another thread try to call those two method, it will fail. </p>
  
  <p><em>Possible solutions</em></p>
  
  <p>1 - Wrap the static into a method like <a href="https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use" rel="nofollow noreferrer">that</a></p>
  
  <pre><code>map&lt;string, string&gt;&amp; getCacheMap()
  {
      static map&lt;string, string&gt; *s_cacheMap = new map&lt;string, string&gt;;
      return *s_cacheMap;
  }
  </code></pre>
  
  <p>2 - Make kv class as singleton</p>
  
  <pre><code>static kv&amp; getInstance()
  {
      static kv* s_kv = new kv();
      return *s_kv;
  }
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>Beside those two solutions, is there any other possible solution for that kind of problem?</p>