Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda: mixed capture list

Tags:

c++

c++11

lambda

Can somebody please show me examples of the following:

1) Lambda that captures x by value. y by reference. What do the rest default to, if unspecified?

2) Lambda that captures x by value. y by reference, all else by value.

3) Lambda that captures x by value. y by reference, all else by reference.

Also, is it allowed that 2 lambdas in the same scope have the same capture signature, such as both be [], or both be [&x, =]

Thanks

like image 824
Baron Yugovich Avatar asked Aug 13 '15 21:08

Baron Yugovich


People also ask

What is a lambda capture list?

The capture clause is used to (indirectly) give a lambda access to variables available in the surrounding scope that it normally would not have access to. All we need to do is list the entities we want to access from within the lambda as part of the capture clause.

What is a lambda expression in C++11?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.

What is capture list in lambda C++?

The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. & (implicitly capture the used automatic variables by reference) and. = (implicitly capture the used automatic variables by copy).

Where are lambda captures stored?

Lambda expressions can capture of outer scope variables into a lambda function. The captured variables are stored in the closure object created for the lambda function.


1 Answers

1) [x, &y](){} rest is not captured

2) [=, &y](){}

3) [&, x](){}

The capture-list is a comma-separated list of zero or more captures, optionally beginning with the capture-default. The only capture defaults are & (by reference) and = (by value). If a capture-default is used, no other captures may use the same capture type. Any capture may appear only once.

Also, is it allowed that 2 lambdas in the same scope have the same capture signature, such as both be [], or both be [&x, =]

Of course it is allowed. Every lambda will be distinct object and have its distinct type. If you capture variable by value in two lambdas, then every lambda will have its copy. If you capture variable by reference in two lambdas, then every lambda will have a reference to the same captured variable.

like image 138
Elohim Meth Avatar answered Sep 20 '22 15:09

Elohim Meth