Is there any difference betwen [=] and [&] in lambda functions?

The difference is how the values are captured

  • & captures by reference
  • = captures by value

Quick example

int x = 1;
auto valueLambda = [=]() { cout << x << endl; };
auto refLambda = [&]() { cout << x << endl; };
x = 13;
valueLambda();
refLambda();

This code will print

1
13

The first lambda captures x by value at the point in which valueLambda is defined. Hence it gets the current value of 1. But the refLambda captures a reference to the local so it sees the up to date value

Leave a Comment