Reputation: 5543
I have a simple class with the following declared privately:
std::mutex headMutex;
std::unique_lock<std::mutex> usingHeadNode(){return std::unique_lock<std::mutex>(headMutex);}
my aim is to provide a simple helper function that returns a unique_lock wrapping the mutex, so that my calling code can be
auto headGuard = usingHeadNode();
to lock the mutex with the RAII technique. However compiling this raises an error:
error: use of deleted function ‘std::lock_guard<_Mutex>::lock_guard(const std::lock_guard<_Mutex>&) [with _Mutex = std::mutex]
... which looks like the constructor for the lock_guard class is missing or something? I haven't deleted anything as far as I'm aware...
Update for more context:
My simple class is a linked list, I want to add a node which involves overwriting the saved head pointer, so I believe I need to lock it to make it safe to modify. A snippet from that add function (can't share the full code as it's an assignment):
// [...]
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
and I'd like to change the locking line to something more readable by wrapping it in a function call somehow
Upvotes: 1
Views: 484
Reputation: 6029
Your problem is that std::unique_lock
is movable but not copyable. Knowing that about the semantics you can see why your code doesn't work - and what's more, you can decide if this technique is appropriate, or, possibly, prone to error.
Upvotes: 1