#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
int main() {
vector<function<void()>> vec;
for (size_t i = 0; i < 10; i++)
{
const int m = i;
auto action = [&] { cout << m << endl; };
vec.push_back(action);
}
for(auto&var:vec)
{
var();
}
system("Pause");
}
输出10个9,将&换成=按值捕获即可得到 0-9
原因
Dangling references
If an entity is captured by reference, implicitly or explicitly, and the function call operator of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of the captured references.
翻译
野引用
如果对一个实体以引用方式捕获,而调用闭包对象的时候已经超过了这个实体的生命周期,无论是直接捕获还是间接捕获,都将会造成未定义行为。
C++闭包不会延长引用方式捕获的元素的生命周期。m的生命周期只限于for循环内,在调用的时候已经结束。
原则上,当for的一次循环结束之后,&m就变成了野指针,你加上const也没有用。所以你当然会读到9个未定义数字和一个9。