> The only gotcha is, there is some overhead involved in this approach. The class instance takes up some space on the stack (several bytes) for every lock acquisition.
Not so fast. A decent compiler will eliminate the overhead and not actually allocate stack space for the lock. Here's an example using one of the lock guards in C++:
struct foo {
int var;
std::mutex m;
};
void process1(foo& f) {
std::lock_guard<std::mutex> lock(f.m);
++f.var;
}
void process2(foo& f) {
f.m.lock();
++f.var;
f.m.unlock();
}
GCC 4.8.1 generates identical code for process1 and process2.