Search code examples
c++c++11mutexdestructorraii

Why is std::mutex::unlock() not noexcept


Why is std::mutex::unlock() not noexept? For some reason the standard leaves the behavior undefined when a thread that does not own the mutex calls unlock() on it. What is the justification for doing so? Doesn't this cause std::unique_lock or std::lock_guard destructors implementations from accidentally leaking exceptions in their destructors if the function throws?

Note Destructors that throw - https://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/


Solution

  • I can't say why the committee didn't make it noexcept. I can only point out the fact that noexcept is - in general - only applied explicitly to a few key functions throughout the standard library that are necessary for implementing efficient functions providing the strong exception guarantee (like std::swap or move constructors).

    As far as std::unique_lock is concerned however: Its destructor IS (implicitly) noexcept, so if an implementation would allow unlock to throw, unique_lock's destructor would have to catch it internally.