error: binding reference of type ‘sylar::RWMutex&’ to ‘const RWMutexType’ {aka ‘const sylar::RWMutex’} discards qualifiers
C++编译的时候,遇到了这个错误。
翻译这个错误就是,将一个 引用类型,绑定到了一个 常量类型上面。这个是不允许的。
In file included from /home/henry/workspace/henry-sylar/tests/test_config.cpp:1: /home/henry/workspace/henry-sylar/tests/../sylar2023/config.h: In instantiation of ‘const T sylar::ConfigVar<T, FromStr, ToStr>::getValue() const [with T = int; FromStr = sylar::LexicalCast<std::basic_string<char>, int>; ToStr = sylar::LexicalCast<int, std::basic_string<char> >]’: /home/henry/workspace/henry-sylar/tests/test_config.cpp:65:82: required from here /home/henry/workspace/henry-sylar/tests/../sylar2023/config.h:279:40: error: binding reference of type ‘sylar::RWMutex&’ to ‘const RWMutexType’ {aka ‘const sylar::RWMutex’} discards qualifiers 279 | RWMutexType::ReadLock lock(m_mutex); | ^~~~~~~ In file included from /home/henry/workspace/henry-sylar/tests/../sylar2023/log.h:16, from /home/henry/workspace/henry-sylar/tests/../sylar2023/config.h:8, from /home/henry/workspace/henry-sylar/tests/test_config.cpp:1: /home/henry/workspace/henry-sylar/tests/../sylar2023/thread.h:70:26: note: initializing argument 1 of ‘sylar::ReadScopedLockImp<T>::ReadScopedLockImp(T&) [with T = sylar::RWMutex]’ 70 | ReadScopedLockImp(T& mutex)
getValue是 常函数。里面的变量都应该是常量。
而我们这里的 m_mutex,是外部的一个引用,不是常量。
因此这里的函数报错了。
RWMutexType m_mutex; const T getValue() const { RWMutexType::ReadLock lock(m_mutex); return m_val; }
解决方案1:将getValue函数的const属性去掉。
解决方案2:声明 m_mutex 的时候,添加mutable属性。getValue还是const函数。
mutable RWMutexType m_mutex;