gpt4 book ai didi

c++ - Lambda:未评估上下文中未捕获的对象

转载 作者:行者123 更新时间:2023-12-02 08:21:35 25 4
gpt4 key购买 nike

我希望指向标准段落,指出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com