如何正确离开关键部分?

Nic*_*ick 8 c++ windows synchronization exception-handling exception

我有以下C++代码,我使用Critical Section对象:

EnterCriticalSection(&cs);

// code that may throw an exception

LeaveCriticalSection(&cs);
Run Code Online (Sandbox Code Playgroud)

LeaveCriticalSection即使抛出异常,如何确保调用该函数?

小智 9

只需使用析构函数进行清理即可:

struct Guard {
  CriticalSection& cs;
  Guard(CriticalSection& cs)
  : cs(cs)
  {
    EnterCriticalSection(cs);
  }
  ~Guard() {
    LeaveCriticalSection(cs);
  }
  Guard(const Guard&) = delete;  
  Guard& operator = (const Guard&) = delete;
};
Run Code Online (Sandbox Code Playgroud)

用法:

void f() {
   Guard guard(cs);
   ...
}
Run Code Online (Sandbox Code Playgroud)


mar*_*inj 8

使用RAII(资源获取是初始化)习语:

struct GuardCS {
    GuardCS(CRITICAL_SECTION& p_cs) : cs(p_cs){
        EnterCriticalSection(&cs);
    }
    ~GuardCS() {
        LeaveCriticalSection(&cs);
    }
private:
    // Protect against copying, remove: =delete on pre c++11 compilers
    GuardCS(GuardCS const &) = delete;
    GuardCS& operator =(GuardCS const &) = delete;
    CRITICAL_SECTION& cs;
};
Run Code Online (Sandbox Code Playgroud)

如果您正在使用MFC,那么有些类可以抽象出这样的东西:Ccriticalsection是否可用于生产?