如何在std :: map中使用boost :: mutex作为映射类型?

时间:2016-04-07 06:28:17

标签: c++ boost mutex stdmap boost-mutex

我想将键/索引锁定在另一个地图中,如下所示:

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

但是,我收到以下错误:

/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) { }
                               ^

它似乎适用于std::vector,但不适用于std::map。我做错了什么?

2 个答案:

答案 0 :(得分:4)

在C ++ 11之前的C ++中,std::map的映射类型在调用operator[]时必须是默认构造和可复制构造。但是,boost::mutex明确地设计为不可复制,因为通常不清楚复制互斥锁的语义应该是什么。由于boost::mutex无法复制,因此使用pointCloudsMutexes_[index]插入此类值无法编译。

最好的解决方法是使用一些指向boost::mutex的共享指针作为映射类型,例如:

#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删除了映射类型可复制构造的要求。

答案 1 :(得分:1)

Map需要一个拷贝构造函数,但遗憾的是boost::mutex没有公共拷贝构造函数。 Mutex声明如下:

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

我认为矢量也不起作用,它应该有同样的问题。你可以push_back boost::mutex进入矢量吗?

相关问题