简体   繁体   中英

using move semantics to initialize class member in constructor

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 delete d 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?

std::mutex is not copyable and not movable. It does not have move constructor or assignment. Library requirements for mutex :

33.4.3.2 Mutex types [thread.mutex.requirements.mutex]
3 The mutex types shall be DefaultConstructible and Destructible . If initialization of an object of a mutex type fails, an exception of type system_error shall be thrown. The mutex types shall not be copyable or movable.

If you want to make your class move constructible then you will need to add another layer of indirection at some point, for example by using std::unique_ptr<std::mutex> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM