如何在C++中定义向量<boost::mutex>?

how to define a vector<boost::mutex> in C++ ?

本文关键字:boost mutex gt lt 定义 向量 C++      更新时间:2023-10-16

我想定义一个boost::互斥的向量:

  boost::mutex myMutex ;
  std::vector< boost::mutex > mutexVec; 
  mutexVec.push_back(myMutex); 

但是,我在Linux上得到错误:

/boost_1_45_0v/include/boost/thread/pthread/mutex.hpp:33: error: boost::mutex::mutex(const boost::mutex&) 是private/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../包括/c++/4.1.2/ext/new_allocator.h: 104:错误:在这种情况下

我在网上找不到解决办法。

谢谢

可以使用boost指针容器:

#include <boost/thread.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
boost::ptr_vector<boost::mutex> pv;
pv.push_back(new boost::mutex);

ptr_vector获得其指针的所有权,以便在适当的时候删除它们,而不会产生智能指针可能带来的任何开销。

复制构造函数是私有的。你不应该复制互斥锁

而不是使用:

boost::mutex *myMutex = new boost::mutex();
std::vector< boost::mutex *> mutexVec; 
mutexVec.push_back(myMutex);

,如果您不想自己管理内存,请使用boost::shared_ptr<boost::mutex>而不是boost::mutex*

boost::mutex不能存储在vector中,因为它不是可复制的。正如peter的回答中提到的,可以将指向互斥锁的指针存储在vector中,但是您真的应该重新考虑依赖于这些东西的设计。请记住,vector本身没有任何线程要求,并且尝试做任何修改vector的操作都不是线程安全的操作。