Lambda capture: use an initializer or not use it?

Consider the following minimal example:

int main() { int x = 10; auto f1 = [x](){ }; auto f2 = [x = x](){}; } 

I have seen this use of the initializer [x = x] more than once, but I cannot fully understand it and why I should use it instead of [x] .
I can get the value of something like [&x = x] or [x = x + 1] (as shown in the documentation and why they differ from [x] , of Of course, but still I can not understand the differences between lambdas in this an example.

Are they completely interchangeable or is there some kind of difference that I don't see?

+5
source share
1 answer

There are various angular cases, which largely come down to " [x = x] decays, [x] does not apply."

  • capture function links:

     void (&f)() = /* ...*/; [f]{}; // the lambda stores a reference to function. [f = f]{}; // the lambda stores a function pointer 
  • array capture:

     int a[2]={}; [a]{} // the lambda stores an array of two ints, copied from 'a' [a = a]{} // the lambda stores an int* 
  • capture of a cv-skilled thing:

     const int i = 0; [i]() mutable { i = 1; } // error; the data member is of type const int [i = i]() mutable { i = 1; } // OK; the data member type is int 
+8
source

Source: https://habr.com/ru/post/1245666/


All Articles