Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ passing a mutex to a member variable in the constructor

I have a problem with passing a mutex to my class. I have a class named Test with the a member variable called m_Mutex. In the constructor I want to transfer the parameter mutex to m_Mutex.

My class:

#include <mutex>

class Test
{
public:
    Test(mutex &mtx) :
        m_Mutex(mtx)
    {
    }

private:
    mutex m_Mutex;
};

My main:

int main()
{
   mutex mutex1;
   Test t(mutex1);
   return 0;
} 

Error:

function "std::mutex::mutex(const std::mutex &)" (declared at line 88 of "c:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.11.25503\include\mutex") cannot be referenced -- it is a deleted function

Why am I getting this error and how can I fix it that I am able to pass the mutex?

like image 493
User987123 Avatar asked Sep 12 '25 07:09

User987123


2 Answers

In short terms: you can't. Mutexes are neither copyable nor movable. And they aren't for a good reason. If however you want to achieve this nontheless, you might pass it by using a unique_ptr:

class A {
   unique_ptr<mutex> mutexPtr;

   A(unique_ptr<mutex> ptr) : mutexPtr(std::move(ptr)) { }
};

A a{std::make_unique<mutex>()};

Note that if you want to share the mutex between different objects, you should use shared_ptr or weak_ptr instead.

like image 145
Jodocus Avatar answered Sep 13 '25 19:09

Jodocus


In the constructor I want to transfer the parameter mutex to m_Mutex

Unfortunately you can't. std::mutex is not copyable and not moveable. One thing you can do if you want to declare the mutex somewhere else is to store a reference to the mutex like

class Test
{
public:
    Test(mutex &mtx) :
        m_Mutex(mtx)
    {
    }

private:
    mutex& m_Mutex;
};
like image 36
NathanOliver Avatar answered Sep 13 '25 20:09

NathanOliver