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