C++局部约束能否调用局部lambda?各编译器实现差异解析
编译行为合规性判定结论
本场景下Clang 13.0.0、MSVC 19.29.29917的编译行为符合C++标准要求,GCC 11.0.1的非内部错误类报错属于实现缺陷。
场景回顾
测试用代码如下:
int main() { auto f = [](unsigned x) { return x == sizeof(int); }; return []<class T>(T) requires (f(sizeof(T))) { return 99; }(12); }
各编译器表现存在差异:
- Clang、MSVC可正常编译上述代码
- GCC在lambda无捕获的情况下拒绝编译,提示
f未被捕获,报错如下:
In substitution of 'template<class T> main()::<lambda(T)> [with T = int]': 3:65: required from here 3:12: required by the constraints of 'template<class T> main()::<lambda(T)>' 3:38: error: 'f' is not captured 3 | return []<class T>(T) requires (f(sizeof(T))) { return 99; }(12); | ~~^~~~~~~~~~~~
- GCC显式按值/按引用捕获
f时仍报相同错误:
error: 'f' is not captured 3 | return [f]<class T>(T) requires (f(sizeof(T))) { return 99; }(12); | ~~^~~~~~~~~~~~ ~^~ what's this then?
- GCC添加默认捕获符(
&按引用或=按值)时触发内部编译器错误(ICE),报错堆栈如下:
3:39: internal compiler error: trying to capture 'f' in instantiation of generic lambda 3 | return [&]<class T>(T) requires (f(sizeof(T))) { return 99; }(12); | ~~^~~~~~~~~~~~ 0x1cfdb99 internal_error(char const*, ...) 0x7ffd56 add_capture(tree_node*, tree_node*, tree_node*, bool, bool) 0x8000ea add_default_capture(tree_node*, tree_node*, tree_node*, tree_node*) 0x73f30a constraints_satisfied_p(tree_node*, tree_node*) 0x954dc3 fn_type_unification(tree_node*, tree_node*, tree_node*, tree_node* const*, unsigned int, tree_node*, unification_kind_t, int, conversion**, bool, bool) 0x6e258e build_op_call(tree_node*, vec<tree_node*, va_gc, vl_embed>**, int) 0x980f05 finish_call_expr(tree_node*, vec<tree_node*, va_gc, vl_embed>**, bool, bool, int) 0x8e173d c_parse_file() 0xa60682 c_common_parse_file()
标准规则依据
按照C++标准的明确规定:
- lambda的
requires子句(约束表达式)属于未求值操作数,不存在潜在求值逻辑,不会触发变量的ODR(单一定义规则)使用判定 - lambda的捕获规则仅适用于以下场景:外层作用域的自动存储期变量,在lambda的函数体或lambda声明符的潜在求值上下文中被ODR使用
- 本场景中
f是main函数内的局部自动变量,仅在未求值的requires子句中被引用,没有发生ODR使用,因此lambda不需要捕获f,未显式写捕获符的代码完全合法
GCC的实现问题说明
- 无捕获时的“未捕获”报错:GCC错误地将未求值上下文中的变量引用判定为需要捕获的ODR使用,违反了标准的ODR与捕获规则
- 显式捕获
f后仍报错:属于额外的实现bug,显式捕获的代码按标准是合法的,编译器应当正确识别已捕获的变量 - 默认捕获触发的ICE:本身就是编译器的实现缺陷,和标准合规性无关
内容的提问来源于stack exchange,提问作者ecatmur
相关产品推荐
相关产品推荐

