I am trying to understand the monitor class that Herb Sutter presented on C++ and Beyond 2012:
template<typename T>
class monitor {
private:
mutable T t;
mutable std::mutex m;
public:
monitor(T t_ = T{}) : t{ t_ } {}
template<typename F>
auto operator()(F f) const -> decltype(f(t))
{
std::lock_guard<std::mutex> _{ m }; return f(t);
}
};
I have managed to create a class that does the same thing in a more old fashioned and simpler (for me at least) way:
template<typename T>
class MyMonitor {
public:
MyMonitor() { t = T(); }
template<typename F>
auto callFunc(F f) {
std::lock_guard<std::mutex> lock(m);
return f(t);
}
private:
T t;
std::mutex m;
};
In which ways are Herb Sutters code better than mine?
In which ways are Herb Sutters code better than mine?
T
should be default constructible, and assignable.In Herb Sutters code, T
should be copy constructible.
Herb Sutters code allows to initialize the member.
Your operator ()
doesn't handle reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With