Lambda capture: to use the initializer or not to u

2019-04-08 20:25发布

问题:

Consider the following, minimal example:

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

I've seen more than once such an use of the initializer [x = x], but I can't fully understand it and why I should use it instead of [x].
I can get the meaning of something like [&x = x] or [x = x + 1] (as shown in the documentation and why they differ from [x], of course, but still I can't figure out the differences between the lambdas in the example.

Are they fully interchangeable or is there any difference I can't see?

回答1:

There are various corner cases that pretty much boils down to "[x = x] decays; [x] doesn't".

  • capturing a reference to function:

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

    int a[2]={};
    [a]{}     // the lambda stores an array of two ints, copied from 'a'
    [a = a]{} // the lambda stores an int*
    
  • capturing a cv-qualified 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's type is int
    


标签: c++ lambda c++14