本文介绍了Herb Sutters如何监控班级工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图理解Herb Sutter在C ++和Beyond 2012上提出的监视器类:
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;
};
在哪些方面Herb Sutters的编码比我的更好?
In which ways are Herb Sutters code better than mine?
推荐答案
- 您的
T
应该是默认可构造且可分配的。 -
在Herb Sutters代码中,
T
应该是可复制构造的。- Your
T
should be default constructible, and assignable. In Herb Sutters code,
T
should be copy constructible.Herb Sutters代码允许初始化成员。
Herb Sutters code allows to initialize the member.
您的
操作符()
不处理引用。这篇关于Herb Sutters如何监控班级工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- Your