class Mutex {
};
void lock(Mutex *pm);
void unlock(Mutex *mp);
class Lock {
public:
explicit Lock(Mutex *pm): mutexPtr(pm) {
lock (mutexPtr);
}
~Lock() {
unlock (mutexPtr);
}
private:
Mutex *mutexPtr;
};
Mutex m;
Lock ml1(&m);
Lock ml2(ml1); // point to same object
I. Prohibit copying
class Uncopyable {
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
class Lock: private Uncopyable {
};
II. Reference-count the underlying resource
tr1::shared_ptr allows specification of a “deleter” - a function or function object to be called when the reference count goes to zero.
class Lock {
public:
explicit Lock(Mutex *pm): mutexPtr(pm, unlock) {
lock(mutexPtr.get());
}
private:
std::tr1::shared_ptr<Mutex> multexPtr;
};