I was watching this talk by Louis Brandy, when a fellow viewer asked this obvious question:
Why does std::unique_lock have a default constructor?
And now I have to know.
There are two primary benefits to using std::unique_lock<> over std::lock_guard<> : you can transfer ownership of the lock between instances, and. the std::unique_lock<> object does not have to own the lock on the mutex it is associated with.
A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.
std::unique_lock The class unique_lock is a general-purpose mutex ownership wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.
look up how a unique_lock() behaves. @Prab, just to give the explanation: unique_lock() is automatically released when the destructor is called meaning it is exception safe and that it automatically unlocks when you leave scope.
unique_lock
is movable. It has a moved-from state that is basically "empty", not associated with any mutex. This state can also be reached by calling release()
.
Given that this state exists, and the benefits of having a default-constructor (such as being able to create arbitrarily-sized dynamic arrays), it's a good idea to add the default constructor that creates the same state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With