title: Safe and effective way to put a mutex on a container entry
body: <p>C++'s <code>std::mutex</code> does not have a move constructor. There is a <a href="https://stackoverflow.com/questions/7557179/move-constructor-for-stdmutex">good reason for that</a>. Basically, move constructors themselves are not generally thread safe, and the whole point of a mutex is that multiple threads will be trying to access it simultaneously.</p>
  
  <p>An unfortunate implication of this is that a mutex cannot be placed into a container directly. Containers need the ability to safely move their contents around, and you can't do that with a mutex.</p>
  
  <p>The easy way out is to just protect the entire container with a single separate mutex. But suppose I want finer-grained control than that? If I'm implementing a database via a container (eg: <code>std::map</code>), it seems reasonable to want the ability to lock individual records, not just the whole database.</p>
  
  <p>The next thing that comes to mind is to hack around the problem by using <code>std::unique_ptr</code>. That would compile, but it doesn't really change the basic problem, does it? The scenario where there's a problem with move is where <code>thread1</code> makes a container change that causes an entry move while <code>thread2</code> is in the middle of using that container entry. In this scenario, <code>thread2</code> could just as easily end up holding a destructed entry or smart pointer. It seems like no matter what, you end up having to lock the entire container with a mutex before doing anything.</p>
  
  <p>It seems like there ought to be a known idiom for doing these kinds of things.</p>