GCC中泛型lambda使用constexpr变量触发-Wunused-but-set-variable误报
GCC
-Wunused-but-set-variable 误报问题:泛型lambda + 模板函数调用场景 问题现象
当同时满足以下条件时,GCC会错误触发-Wunused-but-set-variable警告:
- 使用泛型lambda(即参数带
auto的lambda) - lambda内部引用了外部的
constexpr、const或static变量 - 该lambda通过模板函数被调用
而以下两种场景不会触发该误报:
- 直接调用泛型lambda
- 使用普通lambda(参数为具体类型)配合模板函数调用
示例代码
template<typename F> void call(F f) { f(0); } int main() { // 触发警告:variable 'a' set but not used,const int、static int也会触发 constexpr int a = 0; call([](auto x) { return x == a; }); // 直接调用无问题 constexpr int b = 0; [](auto x) { return x == b; }(0); // 使用普通lambda无问题 constexpr int c = 0; call([](int x) { return x == c; }); }
真实业务场景
这类误报常见于标准库算法调用场景,例如:
constexpr int expectedValue = 123; auto things = getThings(); auto it = std::find_if(things.begin(), things.end(), [](const auto &thing) { return thing.field == expectedValue; });
已知情况
此前已有类似GCC bug报告并被修复,但该问题在GCC 13.1及以下版本中仍然存在,推测是相关bug未完全修复。
临时解决方法
若需快速规避该误报,可采用以下方式:
- 用
[[maybe_unused]]修饰被引用的变量,例如:constexpr [[maybe_unused]] int expectedValue = 123; - 在代码局部临时禁用该警告:
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" // 包含触发警告的代码段 #pragma GCC diagnostic pop
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

