[英]How to use a boost::mutex as the mapped type in 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
. 似乎可以使用std::vector
,但不能使用std::map
。 What am I doing wrong? 我究竟做错了什么?
In C++ before C++11, the mapped type of a std::map
must be both default-constructible and copy-constructible , when calling operator[]
. 在C ++ 11之前的C ++中,在调用operator[]
时, std::map
的映射类型必须是default-constructible和copy-constructible的 。 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. 但是, boost::mutex
被明确设计为不可复制构造的,因为通常不清楚复制互斥量的语义是什么。 Due to boost::mutex
not being copyable, insertion of such value using pointCloudsMutexes_[index]
fails to compile. 由于boost::mutex
无法复制,因此无法使用pointCloudsMutexes_[index]
插入此类值。
The best workaround is to use some shared pointer to boost::mutex
as the mapped type, eg: 最好的解决方法是使用某些共享指针将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 removed the requirement for the mapped type to be copy-constructible. PS:C ++ 11删除了映射类型必须可复制构造的要求。
Map require a copy constructor,but unfortunately boost::mutex
has no public copy constructor. Map需要一个拷贝构造函数,但是不幸的是boost::mutex
没有公共拷贝构造函数。 Mutex declared as below: 互斥体声明如下:
class mutex
{
private:
pthread_mutex_t m;
public:
BOOST_THREAD_NO_COPYABLE(mutex)
I don't think vector works either, it should have same problem. 我也不认为vector也可以,它应该有同样的问题。 Can you push_back
an boost::mutex
into vector? 你可以push_back
一个boost::mutex
入载体?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.