Capture by reference versus capture by value

Using the capture block for referencing and copying variables works just like regular variables. To see the difference, take a look at these two examples and see if you can spot the difference:

Capture by value

Capture by reference

auto func() {  auto vals = {1,2,3,4,5,6};  auto th = 3;  auto is_above=[th](int v){    return v > th;  };  th = 4;  auto count_b=std::count_if(    vals.begin(),    vals.end(),    is_above   );  // count_b equals 3}
auto func() {  auto vals = {1,2,3,4,5,6};    auto th = 3;  auto is_above=[&th](int v){    return v > th;  };  th = 4;  auto count_b=std::count_if(    vals.begin(),    vals.end(),    is_above  );  // count_b equals 2}

In the first example, the threshold was copied into the lambda functions ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.