This is a class that holds mutex and associated object. On checkout/access the mutex is locked while the stack object lives and a reference to object is obtained. Any suggestions or improvements is welcomed.
#include <mutex>
template<class T>
class MutexProtectedObject {
//this relies on benign use and it is just a helper rather than a foolproof solution - ie. anyone may still save a pointer to obj etc. and access it later
public:
class Access {
public:
Access(std::mutex& m, T& obj) : sl_(m), obj_(obj) {
}
T& obj_;
private:
std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
};
Access access() {
return Access(mutex, obj);
}
MutexProtectedObject(const MutexProtectedObject&) = delete;
MutexProtectedObject& opreator=(const MutexProtectedObject&) = delete;
private:
std::mutex mutex;
T obj;
};