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?
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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With