繁体   English   中英

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

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

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

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

在C ++ 11之前的C ++中,在调用operator[]时, std::map的映射类型必须是default-constructible和copy-constructible的 但是, 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删除了映射类型必须可复制构造的要求。

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

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

我也不认为vector也可以,它应该有同样的问题。 你可以push_back一个boost::mutex入载体?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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