如何使用boost :: mutex作为std :: map中的映射类型?(How to use a boost::mutex as the mapped type in std::map?)

编程入门 行业动态 更新时间:2024-10-22 12:33:41
如何使用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不兼容。 我究竟做错了什么?

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?

最满意答案

在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删除了映射类型的要求,以便可复制。

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.

更多推荐

本文发布于:2023-08-05 04:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1427578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   类型   mutex   boost   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!