Reputation: 763
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
}
Upvotes: 5
Views: 2083
Reputation: 38295
Is it a best practice do something similar to this?
std::mutex foo; { std::lock_guard<std::mutex>(foo); // My code which might throw an exception }
No! You are creating an unnamed temporary variable here with a lifetime that ends at the end of the line. Instead, make sure that the object has a name, such that its lifetime meets that of its scope.
std::mutex foo;
{
std::lock_guard<std::mutex> NEVER_FORGET_THIS_NAME(foo);
// My code which might throw an exception
}
But besides, generally - yes, it is good practice to use RAII in this situation. And also note that the unnamed-lockguard bug is not uncommon, have a look here.
Upvotes: 13