jamesatha
jamesatha

Reputation: 7610

Understanding [&] in C++ lambda capture specification

What does this do? Specifically, I have 3 fields out of 20 in 'this' object that I want to pass into the lambda. If I use [&] will it only take the 3 fields I use? And will they be passed by reference or value?

Thanks

Upvotes: 1

Views: 2189

Answers (3)

Dietmar Kühl
Dietmar Kühl

Reputation: 154015

The capture specification tells the compiler how the different variables are meant to be captured. Using [&] means that all variables from the local scope mentioned inside the lambda will be referred to by reference, i.e., they need to stay around as long as the lambda is used. Any changes to these variables will be reflected in the original. You can also use [=] which would store copies of the variables being used. If you want to mix the access, you can set up a default and override the way variables are referred to afterwards, e.g., [=,&foo] captures all variables referred to by value except for foo which captured by reference.

In any case, the lambda object will only store references to or copies of the variables actually being used inside the lambda function or explicitly (by name) mentioned in the capture (thank to jpalecek for pointing out that variables explicitly mentioned are always stored).

In the context mentioned, you mention member variables: these are never captured because they are not in the local scope. What can be captured is this but since it is immutable, it is always captured by value. Speaking of immutable: the variables captures by value by default const. If you want to change them you need to make the the lambda function mutable by mentioning mutable between the parameter list and the body of the lambda function.

Upvotes: 4

Lily Ballard
Lily Ballard

Reputation: 185811

Using [&] as your capture specification in a C++11 lambda simply means that any variable which is referenced inside the lambda will be treated as if it implicitly were specified using &varname in the capture specification. The lambda will not capture any unreferenced variable.

Upvotes: 2

jpalecek
jpalecek

Reputation: 47770

What does this ([&]) do?

It specifies all (implicit) captures are captured by reference. That is, it behaves as if there exists a hidden reference member of the closure object, initialized by the actual captured object.

I have 3 fields out of 20 in 'this' object that I want to pass into the lambda. If I use [&] will it only take the 3 fields I use?

No, if you only capture members of the this object, only the this pointer is captured (always by value).

Upvotes: 8

Related Questions