title: How can I use something like std::vector<std::mutex>?
body: <p>I have a large, but potentially varying, number of objects which are concurrently written into. I want to protect that access with mutexes. To that end, I thought I use a <code>std::vector&lt;std::mutex&gt;</code>, but this doesn't work, since <code>std::mutex</code> has no copy or move constructor, while <code>std::vector::resize()</code> requires that.</p>
  
  <p>What is the recommended solution to this conundrum?</p>
  
  <p><strong>edit</strong>:
  Do all C++ random-access containers require copy or move constructors for re-sizing? Would std::deque help?</p>
  
  <p><strong>edit again</strong></p>
  
  <p>First, thanks for all your thoughts. I'm not interested in solutions that avoid mutices and/or move them into the objects (I refrain from giving details/reasons). So given the problem that I want a adjustable number of mutices (where the adjustment is guaranteed to occur when no mutex is locked), then there appear to be several solutions.</p>
  
  <p><strong>1</strong> I could use a fixed number of mutices and use a hash-function to map from objects to mutices (as in Captain Oblivous's answer). This will result in collisions, but the number of collisions should be small if the number of mutices is much larger than the number of threads, but still smaller than the number of objects.</p>
  
  <p><strong>2</strong> I could define a wrapper class (as in ComicSansMS's answer), e.g.</p>
  
  <pre><code>struct mutex_wrapper : std::mutex
  {
    mutex_wrapper() = default;
    mutex_wrapper(mutex_wrapper const&amp;) noexcept : std::mutex() {}
    bool operator==(mutex_wrapper const&amp;other) noexcept { return this==&amp;other; }
  };
  </code></pre>
  
  <p>and use a <code>std::vector&lt;mutex_wrapper&gt;</code>.</p>
  
  <p><strong>3</strong> I could use <code>std::unique_ptr&lt;std::mutex&gt;</code> to manage individual mutexes (as in Matthias's answer). The problem with this approach is that each mutex is individually allocated and de-allocated on the heap. Therefore, I prefer</p>
  
  <p><strong>4</strong> <code>std::unique_ptr&lt;std::mutex[]&gt; mutices( new std::mutex[n_mutex] );</code></p>
  
  <p>when a certain number <code>n_mutex</code> of mutices is allocated initially. Should this number later be found insufficient, I simply</p>
  
  <pre><code>if(need_mutex &gt; n_mutex) {
    mutices.reset( new std::mutex[need_mutex] );
    n_mutex = need_mutex;
  }
  </code></pre>
  
  <p>So which of these (1,2,4) should I use?</p>