Since when an exception is thrown the only code is ensured to being run is the destructor, code like this might generate a memory leak
std::mutex foo;
foo.lock();
// My code which might throw an exception
foo.unlock();
Is it a best practice do something similar to this or might there is other better option? The idea is taking advantage of RAII in order to ensure than mutex will be freed if exception is thrown.
std::mutex foo;
{
std::lock_guard<std::mutex>(foo);
// My code which might throw an exception
}
std::unique_lock
instead, but there's nothing to be gained by managing mutex manully (except for headache and bugs). – Mingmingchestd::lock_guard<std::mutex>(foo);
does not guard anything since unnamed temporary variable is immediately destroyed so// My code
will be executed when mutex is not locked. – Petepetechia