I'm studying multithreading in C++ and I wrote a simple class that contains a private std::mutex object to synchronize on when a member funcrion is called:
#include <mutex>
#include <iostream>
class SynchClass
{
public:
SynchClass() {}
void inline SynchronizedInterfaceFunction();
private:
std::mutex mMutex;
};
void inline SynchClass::SynchronizedInterfaceFunction()
{
std::lock_guard<std::mutex> lock(mMutex);
for (int i = 0; i < 10; i++)
std::cout << "thread n: " << std::this_thread::get_id() << " inside function" << std::endl;
std::cout << std::endl;
}
Now, I this function has a deleted copy constructor and copy assignment operator, since std::mutex can be moved but not copyed/assigned.
So I provide the class with a move constructor (which is not automatically generated by compiler):
class SynchClass
{
public:
// ... other members as before
SynchClass(SynchClass &&rhs) : mMutex(std::move(rhs.mMutex)) {}
};
but when I ad this line the compiler complains that I'm trying to call the deleted copy constructor of std::mutex:
In file included from main.cpp:5:0:
SynchClass.h: In constructor 'SynchClass::SynchClass(SynchClass&&)':
SynchClass.h:8:61: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
SynchClass(SynchClass &&rhs) : mMutex(std::move(rhs.mMutex)) {}
^
In file included from C:/Program Files/mingw64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/mutex:43:0,
from main.cpp:2:
C:/Program Files/mingw64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
but I'm using std::move to cast the lvalue to an rvalue, so the move constructor of std::mutex should be called.
What am I missing?