boost :: mutex在模板中使用时不起作用

use*_*250 2 c++ templates boost mutex

我正在尝试编写一个类模板:

template<typename ObjType> class SharedBuffer: private boost::noncopyable
Run Code Online (Sandbox Code Playgroud)

我使用boost :: mutex来同步访问缓冲区数据:

private: boost::mutex myMonitor;
Run Code Online (Sandbox Code Playgroud)

但是当我创建锁时,我得到一个奇怪的编译错误:

template<typename ObjType>
inline void SharedBuffer<ObjType>::clear(void){
  boost::mutex::scoped_lock lk(myMonitor);
  myBuffer.clear();
}
Run Code Online (Sandbox Code Playgroud)
Error   9   error C2664: 
'boost::unique_lock<Mutex>::unique_lock(boost::unique_lock<Mutex> &)' :
 cannot convert parameter 1 from
 'const boost::mutex' to 'boost::unique_lock<Mutex> &'
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会这样.我没有将myMonitor声明为常量.我正在使用VS2010并提升1.4.9

ink*_*boo 6

有问题:

无法将参数1从' const boost :: mutex'转换为'boost :: unique_lock&'

解决方案是:

private:mutable boost :: mutex myMonitor;

  • 你能详细说明一下吗?确切地说**为什么**是非常量方法中的互斥体突然const.是允许所有const方法能够更改互斥锁的唯一解决方案吗? (2认同)