简体   繁体   English

C++ lambda 捕获结果

[英]C++ lambda capture result

For example I have next code:例如我有下一个代码:

int func() 
{
    int i = 0;
    int j = 0;
    auto lambda{[&](){ return i; }};
    return lambda();
}

Will be j captured also by reference or lambda captures only objects that it uses? j也会被引用捕获还是 lambda 仅捕获它使用的对象?

No, j won't be captured不, j不会被捕获

From Lambda capture docs:Lambda 捕获文档:

& (implicitly capture the used automatic variables by reference) &(通过引用隐式捕获使用的自动变量)

Note the word "used"注意“使用”这个词

No, j will not be captured.不, j不会被捕获。

From https://en.cppreference.com/w/cpp/language/lambda :https://en.cppreference.com/w/cpp/language/lambda

The captures is a comma-separated list of zero or more captures, optionally beginning with the capture-default.捕获是零个或多个捕获的逗号分隔列表,可选择以捕获默认值开头。 The only capture defaults are唯一的捕获默认值是

  • & (implicitly capture the used automatic variables by reference) and &(通过引用隐式捕获使用的自动变量)和
  • = (implicitly capture the used automatic variables by copy). =(通过复制隐式捕获使用的自动变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM