Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 move when returning a lock

People also ask

Is unique_lock movable?

But a unique_lock does not really have to own a lock. Therefore, it can be moved to transfer the ownership of the held lock to another scope. The compiler automatically moves a unique_lock if it is a prvalue returned from a function, or a unique_lock variable can be moved explicitly via std::move.

Can mutex be moved?

The mutex will not be moved - it will be constructed in-place at the caller's location, but the callee (eg: make_mutex ) gets to decide how to do that construction.

What is the benefit of using STD unique lock <> between instances?

The benefit to using std::unique_lock<> comes from two things: 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.


It's fine with or without the std::move. The name of a local variable* is treated as an rvalue in the return statement, causing the move constructor to be invoked in both cases. The authors presumably used std::move for stylistic reasons, to make it clear that the lock is being moved. It does interfere with NRVO, but the cost of moving a unique_lock here is probably minimal compared to the cost of the lock and the wait.

In @Deduplicator's words, it's "a pessimization in order to emphasize the actual semantics".

You can test this yourself - unique_lock can't be copied, so return head_lock; wouldn't have compiled if it were a copy.


* This is the C++14 rule. The C++11 rule is restricted to cases where copy elision is allowed or would be allowed except for the fact that the variable is a function parameter. This difference is immaterial as far as this question is concerned, since head_lock obviously qualifies for copy elision.