Implementing unique_unlock, the opposite of std::unique_lock

Viewed 68

I have a situation where an std::mutex needs to be locked most of the time, except when inside a specific scope. I was thinking there should be an opposite of std::unique_lock that unlock()s on construction and the lock()s on destruction.
Should be something as simple as

template<typename M>
class unique_unlock
{
public:
    unique_unlock(M& m) : m_(m) {
        m_.unlock();
    }
    ~unique_unlock() {
        m_.lock();
    }
private:
    M& m_;
};

Is there any issue with this approach?

1 Answers

std::mutex::lock is documented to throw std::system_error, which would cause your destructor to throw. You need an explicit noexcept(false) to override the implicit noexcept(true).

That's so unusual that you probably should also warn the users of your class about this. This appears to be a RAII scope guard class, but if this dtor runs during stack unwinding (as is the intent with RAII) then that second exception will std::terminate the program.

Related