Lambda capture: to use the initializer or not to use it?

纵饮孤独 提交于 2019-12-21 16:59:27

问题


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
    


来源:https://stackoverflow.com/questions/36188694/lambda-capture-to-use-the-initializer-or-not-to-use-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!