How to use a boost::mutex as the mapped type in std::map?

会有一股神秘感。 提交于 2019-12-12 11:13:12

问题


I would like to lock the keys/index in another map like this:

std::map<int, boost::mutex> pointCloudsMutexes_;
pointCloudsMutexes_[index].lock();

However, I am getting the following error:

/usr/include/c++/4.8/bits/stl_pair.h:113: error: no matching function for call to 'boost::mutex::mutex(const boost::mutex&)'
       : first(__a), second(__b) { }
                               ^

It seems to work with std::vector, but not with std::map. What am I doing wrong?


回答1:


In C++ before C++11, the mapped type of a std::map must be both default-constructible and copy-constructible, when calling operator[]. However, boost::mutex is explicitly designed not to be copy-constructible, because it is generally unclear what the semantics of copying a mutex should be. Due to boost::mutex not being copyable, insertion of such value using pointCloudsMutexes_[index] fails to compile.

The best workaround is to use some shared pointer to boost::mutex as the mapped type, e.g:

#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <map>

struct MyMutexWrapper {
    MyMutexWrapper() : ptr(new boost::mutex()) {}
    void lock() { ptr->lock(); }
    void unlock() { ptr->unlock(); }
    boost::shared_ptr<boost::mutex> ptr;
};

int main() {
    int const index = 42;
    std::map<int, MyMutexWrapper> pm;
    pm[index].lock();
}

PS: C++11 removed the requirement for the mapped type to be copy-constructible.




回答2:


Map require a copy constructor,but unfortunately boost::mutex has no public copy constructor. Mutex declared as below:

class mutex
{
private:
    pthread_mutex_t m;
public:
    BOOST_THREAD_NO_COPYABLE(mutex)

I don't think vector works either, it should have same problem. Can you push_back an boost::mutex into vector?



来源:https://stackoverflow.com/questions/36468270/how-to-use-a-boostmutex-as-the-mapped-type-in-stdmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!