Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::unique_lock have a default constructor?

Tags:

c++

std

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.

like image 795
deworde Avatar asked Nov 28 '17 16:11

deworde


People also ask

What is the benefit of using std :: unique_lock?

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.

What is the difference between unique_lock and Lock_guard?

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.

What is std :: unique_lock?

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.

Does unique_lock automatically unlock?

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.


1 Answers

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.

like image 144
Sebastian Redl Avatar answered Nov 04 '22 23:11

Sebastian Redl