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 ...