简体   繁体   English

无法将参数1从&#39;const boost :: shared_mutex&#39;转换为&#39;const boost :: shared_lock <Mutex> &”

[英]cannot convert parameter 1 from 'const boost::shared_mutex' to 'const boost::shared_lock<Mutex> &'

I am just trying to implement this answer about mutexes with over 100 upvotes . 我只是试图实现这个关于超过100个upvotes的互斥量的答案 All I did was copy paste the code, so that my class reads (simplified) like this: 我所做的只是复制粘贴代码,以便我的类读取(简化)如下:

mymutexclass.h

class MyMutexClass {
public:
    void write( uint32_t id, const std::string &str );
    std::string read( uint32_t id ) const;

private:
    boost::shared_mutex _access;
    std::map<uint32_t, std::string> strings;
};

mymutexclass.cpp

void MyMutexClass::write( uint32_t id, const std::string &str ) {
    boost::unique_lock< boost::shared_mutex > lock(_access);
    strings[id] = name;
}
std::string MyMutexClass::read( const uint32_t id ) const {
    boost::shared_lock< boost::shared_mutex > lock(_access); // ERROR HERE
    if( strings.count( id )>0) 
        return strings.at(id);
    else
        return "No value.";
}

And I get an error, only for the read mutex line: 我得到一个错误,只有读取互斥线:

error C2664: 'boost::shared_lock<Mutex>::shared_lock(const boost::shared_lock<Mutex> &)' : cannot convert parameter 1 from 'const boost::shared_mutex' to 'const boost::shared_lock<Mutex> &'   D:\... path ...\mymutexclass.cpp

I am completely lost in the error - what's the difference between the types it complains about? 我完全迷失在错误中 - 它抱怨的类型有什么区别? I mean these, from the error: 我的意思是这些,从错误:

  • from const boost::shared_mutex 来自const boost::shared_mutex
  • to const boost::shared_lock<Mutex> & to const boost::shared_lock<Mutex> &

And what am I doing wrong? 我做错了什么? That linked answer was upvoted 100 times, so I guess it's really likely to be correct. 这个相关的答案被提升了100次,所以我猜这很可能是正确的。

Because your method has a const signature, you are not allowed to change the mutex state, hence you are not allowed to lock it. 由于您的方法具有const签名,因此不允许更改互斥锁状态,因此不允许您锁定它。 Changing the mutex to mutable should fix the error: 将互斥锁更改为mutable可以修复错误:

mutable boost::shared_mutex _access;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM