考虑以下最小示例:
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/