Raa*_*aaj 5 c++ boost mutex stdmap boost-mutex
我想在其他地图中锁定键/索引,如下所示:
std::map<int, boost::mutex> pointCloudsMutexes_;
pointCloudsMutexes_[index].lock();
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
/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) { }
^
Run Code Online (Sandbox Code Playgroud)
它似乎可以使用std::vector,但不是std::map.我究竟做错了什么?
在 C++11 之前的 C++ 中,调用 时, a 的映射类型std::map必须既可默认构造又可复制构造operator[]。然而,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();
}
Run Code Online (Sandbox Code Playgroud)
PS:C++11 删除了映射类型可复制构造的要求。
| 归档时间: |
|
| 查看次数: |
465 次 |
| 最近记录: |