gpt4 book ai didi

c++ - 为什么在 lambda 中隐式捕获 const ints(或短裤)?

转载 作者:IT老高 更新时间:2023-10-28 14:00:29 25 4
gpt4 key购买 nike

这样编译:

int main() {
const int x = 123;
auto g = []() { std::cout << x << "\n"; };
g();
}

但是这个:

int main(){
const float x = 123;
auto g = []() { std::cout << x << "\n"; };
g();
}

产生:

"error: 'x' is not captured"

为什么?

我已经在 GCC(从 5.0.0 到 8.0.0 的各种版本)和 Clang(从 4.0.0 到 6.0.0 的各种版本)上对其进行了测试。它在所有情况下的行为都相同。

最佳答案

Lambda 的作用域可以隐式捕获其到达作用域内的变量。

您的变量在到达范围内,因为它们是定义 lambda 的(主)函数的本地变量。

但是,如 [expr.prim.lambda]/12 中所述,通过这种机制可以捕获变量有一些标准。 :

A lambda-expression with an associated capture-default that does not explicitly capture this or a variable with automatic storage duration [..], is said to implicitly capture the entity (i.e., this or a variable) if the compound-statement:

-odr-uses ([basic.def.odr]) the entity, or

-names the entity in a potentially-evaluated expression ([basic.def.odr]) where the enclosing full-expression depends on a generic lambda parameter declared within the reaching scope of the lambda-expression.

最重要的部分在[expr.const]/2.7 :

A conditional-expression e is a core constant expression unless the evaluation of e, [..] would evaluate one of the following expressions:

an lvalue-to-rvalue conversion ([conv.lval]) unless it is applied to:

a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression.

所以 const int 是一个 核心常量表达式const float 不是。

此外[expr.const]1826提及:

A const integer initialized with a constant can be used in constant expressions, but a const floating point variable initialized with a constant cannot.

阅读更多 Why is a const variable sometimes not required to be captured in a lambda?

关于c++ - 为什么在 lambda 中隐式捕获 const ints(或短裤)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724260/

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