On 10/02/2020 05:23 AM, John W. Eaton
wrote:
On
10/1/20 8:13 PM, Rik wrote:
On 10/01/2020 12:42 PM, John W. Eaton
wrote:
We could also decide to always use "[=]"
when we need to capture something. Then all variables that
are needed, including "this" will be captured using the
default rules for capture by value.
I don't think this is recommended practice. The temporary
anonymous struct that is created to represent the lambda
_expression_ will then have an argument in the constructor for
every existing variable in the surrounding function. The
compiler *might* then optimize out all of the additional unused
captures, but I think it would be better to just capture what
you need either by value "[=variable_name]" if small like a
built-in type or a pointer or by reference
"[&variable_name]" if it is something large like the
instance of a class. For reference, I was using this
https://dzone.com/articles/all-about-lambda-functions-in-cfrom-c11-to-c17.
As I understand it, the lambda _expression_ only captures variables
that are used. Using a capture default specification actually
seems better to me because the variables are already listed in the
lambda _expression_, so explicitly listing them again is redundant.
To me, this seems quite similar to using "auto" to avoid writing
out something that the compiler can figure out. I don't know why
the article you linked lists [=] and [&] as not recommended.
I didn't see an explanation and I'm not finding other similar
recommendations.
jwe,
Just to fully close this issue, I created a function with a 1000
local variables and a lambda _expression_ that used one of the
variables. I defined the capture _expression_ as either "[=]" or
"[=var995]" which captures just one variable. I then compiled with
gcc and compared the resulting binaries. At least with gcc, there
is no particular binary difference between using either _expression_
which indicates it is safe to capture all variables as the compiler
is smart enough to optimize out anything that is unused. So, I
think we're fine with adopting the conventions you proposed.
--Rik
|