Lambda捕获:使用初始化器还是不使用它?

时间:2016-03-23 21:07:19

标签: c++ lambda c++14

考虑以下最小例子:

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

我已经多次使用初始化程序[x = x],但我无法完全理解它以及为什么我应该使用它而不是[x]
我可以得到[&x = x][x = x + 1]之类的含义(如documentation中所示,以及为什么它们与[x]不同,当然,我仍然可以'弄清楚示例中lambda之间的差异。

它们是完全可以互换的还是有什么区别我无法看到?

1 个答案:

答案 0 :(得分:8)

有各种各样的角落案例几乎归结为" [x = x]衰变; [x]没有"。

  • 捕获对函数的引用:

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

    int a[2]={};
    [a]{}     // the lambda stores an array of two ints, copied from 'a'
    [a = a]{} // the lambda stores an int*
    
  • 捕获符合cv标准的内容:

    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