Is it a bad practice to always capture all in a lambda expression? [duplicate]

Performance

The standard guarantees that if you do a default capture, the only variables that will be captured by that default capture from the surrounding environment are those that you actually use inside the lambda.

As such, specifying individual variables to capture acts as documentation of what you expect to use, but should never affect performance.

For anybody who cares, the exact wording from the standard is (ยง5.1.2/11, 12):

11 If a lambda-expression has an associated capture-default and its compound-statement odr-uses (3.2) this or a variable with automatic storage duration and the odr-used entity is not explicitly captured, then the odr-used entity is said to be implicitly captured; such entities shall be declared within the reaching scope of the lambda expression. [Note elided]

12 An entity is captured if it is captured explicitly or implicitly. […]

Readability

Opinions seems split on this point. Some people like the documentation of intent that comes with explicitly specifying what you capture. Others see this as visual noise that mostly gets in the way of understanding what the lambda is/does.

Personally, I think it’s usually kind of irrelevant–most lambadas are (and should be) quite small and simple, and only need to capture a few things. As such, explicit documentation of what they capture doesn’t add much noise, but also doesn’t add much to making the code more understandable. If explicit capture makes a huge difference in either direction, that may hint at there being other problems with the code.

Summary

An implicit capture specification ([=] or [&]) will only capture variables that are used in the lambda, so implicit vs. explicit capture should never affect performance.

I don’t think there’s a simple, clear answer with respect to readability.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)