我有以下 C++ 代码,我在其中使用临界区对象 https://msdn.microsoft.com/en-us/library/windows/desktop/ms682530(v=vs.85).aspx:
EnterCriticalSection(&cs);
// code that may throw an exception
LeaveCriticalSection(&cs);
我怎样才能确保LeaveCriticalSection
即使抛出异常也会调用函数?
只需编写一个使用析构函数进行清理的守卫:
struct Guard {
CriticalSection& cs;
Guard(CriticalSection& cs)
: cs(cs)
{
EnterCriticalSection(cs);
}
~Guard() {
LeaveCriticalSection(cs);
}
Guard(const Guard&) = delete;
Guard& operator = (const Guard&) = delete;
};
Usage:
void f() {
Guard guard(cs);
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)