Hacker News new | past | comments | ask | show | jobs | submit login

In that code from the article:

  const auto ageNext = fetchFromCache(userId)
        .or_else([&]() { return fetchFromServer(userId); })
        .and_then(extractAge)
        .transform([](int age) { return age + 1; });
what is the meaning of the & in the first lambda?



The & captures the `userId` by reference and makes it available in the lambda body.


The `&` captures the surrounding variables by reference. This means that the lambda will have access to variables defined in the scope where the lambda is declared, without making a copy of them. In this case, `userId` is captured by reference, so any changes to `userId` outside the lambda would be reflected inside the lambda as well.


It causes userId to be captured by reference. Compare with [=] which would capture by value.


Thank you grumbel and yrro, I get it. I'm used to write things like [&userId]() and was ignorant of "implicit" capture.

Is there a benefit to the explicit version or is this purely a stylistic matter?


Implicit capture may capture more than you intended to. Explicit will cause the compiler to alert you to other names you might not have realized you included. It also makes it harder for people modifying your code to mess it up.

That said, I usually use implicit because if I'm writing a lambda it's in a highly local context where a) it's just a shortcut, b) I know exactly what I'm doing, and c) it's not really meant for usability.

If you want to make the intent really explicit and rigid, it might even be better to use a structured capturing type with an operator(): `MyCapture{.x = x, .y = y}()` or whatever.


Implicit captures may not be obvious and may be accidental, leading to lifetime issues. Without a borrow checker like rust, it's safer to name them explicitly most of the time.


I wish we had the option to specify explicit captures in rust closures too. When you need it you need it, and it is good for clarity. The current "add `move` to switch from by-reference to by-value" is too coarse grained




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: