c++ - Lambda 捕获 : to use the initializer or not to use it?

标签 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 之间的区别。

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

最佳答案

有各种极端情况几乎可以归结为“[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
    

关于c++ - Lambda 捕获 : to use the initializer or not to use it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188694/

相关文章:

Ruby:从内部 block 产生不起作用

c++ - 如何将通用 packaged_tasks 存储在容器中?

c++ - 是否可以找出多态 C++ 14 lambda 的参数类型和返回类型?

c++ - 当子类定义新的成员变量时,我可以避免 dynamic_cast 吗?

c++ - 当相应的对象作为 const 传递时,我如何迭代一个 vector 作为类的成员

c++ - 无法在线程中专门化函数模板

c++ - OSX 上不兼容的 openCV 和 libtiff 库

c++ - 如何使用 Linux getrandom 系统调用生成一个范围内的随机数?

c# - 计算复杂的 lambda 表达式

lambda - 使用 lambda 提供基于堆栈的上下文(例如文件操作的路径)