问题描述
std::mutex headMutex;
std::unique_lock<std::mutex> usingHeadNode(){return std::unique_lock<std::mutex>(headMutex);}
我的目标是提供一个简单的辅助函数,它返回一个包装互斥锁的 unique_lock,以便我的调用代码可以
auto headGuard = usingHeadNode();
使用 RAII 技术锁定互斥锁。但是编译这个会产生一个错误:
错误:使用删除的函数 'std::lock_guard<_mutex>::lock_guard(const std::lock_guard<_mutex>&) [使用 _Mutex = std::mutex]
... 看起来 lock_guard 类的构造函数丢失了还是什么?据我所知,我还没有删除任何东西...
更新更多上下文:
我的简单类是一个链表,我想添加一个涉及覆盖保存的头指针的节点,所以我相信我需要锁定它以使其安全修改。来自该 add 函数的片段(无法共享完整代码,因为它是一项任务):
// [...]
Node * pNewNode = new Node(value);
//Link it in by prepending
std::unique_lock<std::mutex> pHeadGuard(headMutex); //= usingHeadNode();
pNewNode->prev = nullptr; //since we prepend and this is the new head,there is no 'prevIoUs' element
pNewNode->next = pHead; //what was the head Now comes after the new node
// [...]
pHead = pNewNode; // this is why we needed the mutex
我想通过以某种方式将锁定行包装在函数调用中来将其更改为更具可读性的内容
解决方法
您的问题是 std::unique_lock
is movable but not copyable。了解语义后,您就可以了解为什么您的代码不起作用 - 而且,您可以决定这种技术是否合适,或者是否容易出错。