5

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

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。我究竟做错了什么?

4

2 回答 2

4

在 C++11 之前的 C++ 中std::map在调用. 但是,它被明确设计为不可复制构造,因为通常不清楚复制互斥体的语义应该是什么。由于不可复制,插入此类值 using无法编译。operator[]boost::mutexboost::mutexpointCloudsMutexes_[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 删除了映射类型是可复制构造的要求。

于 2016-04-07T07:46:20.617 回答
1

Map 需要一个拷贝构造函数,但不幸boost::mutex的是没有公共拷贝构造函数。互斥锁声明如下:

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

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

于 2016-04-07T07:42:38.197 回答