简体   繁体   English

C ++ lambda按值捕获而无需提前声明变量

[英]C++ lambda capture by value without declaring variable earlier

Looking at the example on the page: 查看页面上的示例:

https://en.cppreference.com/w/cpp/algorithm/generate https://en.cppreference.com/w/cpp/algorithm/generate

It uses a lambda: 它使用lambda:

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

the variable n is not declared anywhere prior to the lambda. 变量n不在lambda之前的任何地方声明。

Having tried this snippet in MSVC 14 and GCC 9.1, it does work on both. 在MSVC 14和GCC 9.1中尝试了此代码段后,它确实可以在两者上正常工作。

Try to find a reference to this behaviour at: 尝试在以下位置找到对此行为的引用:

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

but cannot find anywhere where it says that new variables can be declared in the capture region of a lambda. 但找不到可以在lambda的捕获区域中声明新变量的地方。

Is this expected behaviour? 这是预期的行为吗? What are the restrictions if it is? 有什么限制?

In the reference you link to, it's in the lambda capture section , item number 3 in the list. 在您链接到的参考中,它位于lambda捕获部分中 ,列表中的项目编号3。

And from further down (in a "since C++14" section): 然后再往下(在“ C ++ 14起”部分):

A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto 使用初始化程序进行捕获的方式就像声明并显式捕获使用auto类型声明的变量一样

[Emphasis mine] [强调我的]

Which explicitly explains the behavior of that capture clause. 其中明确解释了该捕获子句的行为。

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

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