title: Locking a mutex in a destructor in C++11
body: <p>I have some code which need to be thread safe and exception safe. The code below is a very simplified version of my problem :</p>
  
  <pre><code>#include &lt;mutex&gt;
  #include &lt;thread&gt;
  
  std::mutex mutex;
  int n=0;
  
  class Counter{
  public:
      Counter(){
          std::lock_guard&lt;std::mutex&gt;guard(mutex);
          n++;}
      ~Counter(){
          std::lock_guard&lt;std::mutex&gt;guard(mutex);//How can I protect here the underlying code to mutex.lock() ?
          n--;}
  };
  
  void doSomething(){
      Counter counter;
      //Here I could do something meaningful
  }
  
  int numberOfThreadInDoSomething(){
      std::lock_guard&lt;std::mutex&gt;guard(mutex);
      return n;}
  </code></pre>
  
  <p>I have a mutex that I need to lock in the destructor of an object. The problem is that my destructor should not throw exceptions.</p>
  
  <p>What can I do ?</p>
  
  <p>0) I cannot replace <code>n</code> with an atomic variable (of course it would do the trick here but that is not the point of my question)</p>
  
  <p>1) I could replace my mutex with a spin lock</p>
  
  <p>2) I could try and catch the locking into an infinite loop until I eventualy acquire the lock with no exception raised</p>
  
  <p>None of those solution seems very appealing. Did you have the same problem ? How did you solve it ?</p>