返回锁定时C ++ 11移动

时间:2014-09-24 10:17:47

标签: c++ c++11 move-semantics rvo

在书中" C ++并发行动"阅读以下方法

std::unique_lock<std::mutex> wait_for_data()
{
    std::unique_lock<std::mutex> head_lock(head_mutex);
    data_cond.wait(head_lock,[&]{return head.get()!=get_tail();});
    return std::move(head_lock);
 }

我无法理解为什么返回时head_lock是std :: move-ed。我对移动用法和RVO的观念和直觉与C++11 rvalues and move semantics confusion (return statement)

中分享的观点相符

但我倾向于相信作者更了解。有人可以澄清什么时候std :: move返回值更好并且是否有关于锁的具体内容?感谢。

1 个答案:

答案 0 :(得分:25)

无论是否有std::move,都没问题。局部变量 * 的名称在return语句中被视为右值,导致在两种情况下都调用移动构造函数。由于风格原因,作者可能会使用std::move来明确锁定是否被移动。它确实干扰了NRVO,但是与锁定和等待的成本相比,在这里移动unique_lock的成本可能是最小的。

在@ Deduplicator的话中,它是一种悲观化,以强调实际的语义&#34;。

您可以自行测试 - unique_lock无法复制,因此return head_lock;如果是副本则不会编译。


* 这是C ++ 14规则。 C ++ 11规则是restricted to cases where copy elision is allowed or would be allowed except for the fact that the variable is a function parameter。就这个问题而言,这种差异并不重要,因为head_lock显然有资格获得复制。