108

I want to know what [=] does? Here's a short example

template <typename T>
std::function<T (T)> makeConverter(T factor, T offset) {
    return [=] (T input) -> T { return (offset + input) * factor; };
}

auto milesToKm = makeConverter(1.60936, 0.0);

How would the code work with [] instead of [=]?

I assume that

std::function<T (T)>

means an function prototype which gets (T) as argument and return type T?

0

3 Answers 3

124

The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created. This is necessary for the lambda expression to be able to refer to factor and offset, which are local variables inside the function.

If you replace the [=] with [], you'll get a compiler error because the code inside the lambda expression won't know what the variables offset and factor refer to. Many compilers give good diagnostic error messages if you do this, so try it and see what happens!

3
  • 14
    "This is necessary" - this exact option isn't necessary; we could also write [&], [=offset, =input], etc.
    – M.M
    Jan 14, 2016 at 4:03
  • 1
    @M.M - Doesn't that capture references to locals?
    – Useless
    Jan 14, 2016 at 17:14
  • 7
    @M.M. Using a reference capture here would be a problem because those local variables' lifetimes will end as soon as the lambda is returned. You're right that we could list the individual variables individually, though. Jan 14, 2016 at 17:27
51

It's a lambda capture list. Makes variables available for the lambda. You can use [=] which copies by value, or [&] which passes by reference.

1
  • 4
    You can also use [] which doesn't capture anything. :) Jan 19, 2016 at 22:15
1

I would use comment to provide this information, but I have too low reputation.

In cpp20 using [=] is now deprecated - use [=, this] instead.

More information here: https://isocpp.org/files/papers/p0806r2.html

As it is stated on this website "The change does not break otherwise valid C++20 code, and the earliest revision in which a breakage from C++17 could appear is C++23."

So while using cpp20 use it like this:

  • [=] → [=, this]: local variables by value, class members by reference
  • [=] → [=, *this]: everything by value
  • [&] → [&, this]: everything by reference
  • [&] → [&, *this]: (this would be unusual)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.