RAII - cppreference.comhttps://en.cppreference.com/w/cpp/language/raii
std::mutex m; void bad() { m.lock(); // acquire the mutex f(); // if f() throws an exception, the mutex is never released if(!everything_ok()) return; // early return, the mutex is never released m.unlock(); // if bad() reaches this statement, the mutex is released } void good() { std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization f(); // if f() throws an exception, the mutex is released if(!everything_ok()) return; // early return, the mutex is released }
lock_guard构造时lock mutex ,析构时unlock mutex。bad中m忘了unlock。使用RAII可以避免出现这种错误。