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;
分类:
B.1.1-C/C++ 基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2020-01-01 【动态规划专题】6:打气球的最大分数