Locking a mutex in a destructor in C++11
I have some code which need to be thread safe and exception safe. The code below is a very simplified version of my problem : #include <mutex> #include <thread> std::mutex mutex; int n=0; class Counter{ public: Counter(){ std::lock_guard<std::mutex>guard(mutex); n++;} ~Counter(){ std::lock_guard<std::mutex>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<std::mutex>guard(mutex); return n;} I have a mutex that I need to lock in the