title: Returning an RAII container class that holds a std::mutex lock
body: <p>I'd like to wrap all usages of a class instance with a mutex. Today I have</p>
  
  <pre><code>std::map&lt;int, std::shared_ptr&lt;MyClass&gt;&gt; classes;
  </code></pre>
  
  <p>and functions to find and return instances, like:</p>
  
  <pre><code>std::shared_ptr&lt;MyClass&gt; GetClass(int i);
  </code></pre>
  
  <p>I'd like to ensure that GetClass() can only retrieve an instance if someone else hasn't already retrieved it, with some RAII mechanism. Usage would be like:</p>
  
  <pre><code>void CallingFunction()
  {
      auto c = GetClass(i); // mutex for class id 'i' is acquired here
  
      // some calls to class
      c.SomeFunction();
  } // mutex is released here when 'c' goes out of scope
  </code></pre>
  
  <p>With the mutex acquired by CallingFunction() other threads that wanted to access the same class instance would block on their calls to GetClass().</p>
  
  <p>I've been looking at a few ways of doing it, such as with a wrapper class like:</p>
  
  <pre><code>class ClassContainer
  {
      public:
          std::shared_ptr&lt;Class&gt; c;
          std::mutex m;
  };
  </code></pre>
  
  <p>Where I'd modify GetClass() to be:</p>
  
  <pre><code>ClassContainer GetClass(int i);
  </code></pre>
  
  <p>But I'm having trouble figuring out both where the std::mutex should be kept, I tried initially storing it in the map before moving to using a container class like:</p>
  
  <pre><code>std::map&lt;int, std::pair&lt;std::mutex, std::shared_ptr&lt;MyClass&lt;&gt;&gt;&gt; classes;
  </code></pre>
  
  <p>but that wasn't working well, now with the ClassContainer how to have ClassContainer lock the std::mutex like std::lock_guard&lt;> when the caller acquires one via a call to GetClass().</p>