以下代码工作正常:
#include <iostream>
#include <functional>
std::function<int (void)> get_incrementer() {
return []() {
static int count = 0;
return count++;
};
}
int main() {
using std::cout;
auto incrementer = get_incrementer();
cout << incrementer() << std::endl;
cout << incrementer() << std::endl;
return 0;
}
但是,如果您改为通过引用捕获局部变量,它会突然导致未定义的行为,这可能是因为在调用时堆栈上的该位置正被其他东西使用。
std::function<int (void)> get_incrementer() {
int count = 0;
return [&count]() {
return count++;
};
}
为什么编译器允许它呢?我希望编译器要么不允许这样做(检查这种情况似乎很简单),要么更改局部变量的存储持续时间。