如何使用一个boost ::互斥作为的std ::地图映射的类型? [英] How to use a boost::mutex as the mapped type in std::map?

查看:189
本文介绍了如何使用一个boost ::互斥作为的std ::地图映射的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想锁定按键/指数另一个地图是这样的:

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

这似乎与工作的std ::矢量,但不能与的std ::地图。我在做什么错了?

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

推荐答案

在C ++中,的std ::地图的映射类型必须是默认构造的和拷贝构造,当调用运算符[] 。然而,的boost ::互斥明确设计不被拷贝构造,因为它通常是不清楚复制一个互斥体的语义应该是什么。由于的boost ::互斥不是可复制,使用 pointCloudsMutexes_ [指数] 这样的价值插入编译失败。

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.

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

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移除的映射类型为拷贝构造的要求

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

这篇关于如何使用一个boost ::互斥作为的std ::地图映射的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆