简体   繁体   中英

What does [=] mean in C++?

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 ?

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!

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM