我希望指向标准段落,指出 following code格式良好:
int main() {
int var = 0;
return [] { return sizeof(var); }(); // var is not captured!
}
类似的例子出现,例如§ 8.4.5.2,但我找不到任何口头描述。
最佳答案
它是根据何时必须捕获实体来指定的,而不是根据何时不能捕获实体来指定。
[expr.prim.lambda.capture] (with some omissions)
8 ... If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression. ...
[ Example:
void f1(int i) { int const N = 20; auto m1 = [=]{ int const M = 30; auto m2 = [i]{ int x[N][M]; // OK: N and M are not odr-used // ... }; }; // ... }
— end example ]
代码示例中的关键是 var
未使用 odr,因为它是未计算的操作数。因此,不需要捕获它。
关于c++ - Lambda:未评估上下文中未捕获的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264055/