我正在尝试学习 C++ 中闭包的概念。我有以下代码。
std::function<void(void)> closureWrapper2()
{
int x = 10;
return [&x](){x += 1; std::cout << "Value in the closure: " << x << std::endl;};
}
int main()
{
std::function<void(void)> func2 = closureWrapper2();
// std::cout << "---" << std::endl;
func2();
func2();
func2();
}
输出
Value in the closure: 11
Value in the closure: 12
Value in the closure: 13
现在,如果我取消对 cout
语句的注释,我会得到以下输出。
输出
---
Value in the closure: 32765
Value in the closure: 32766
Value in the closure: 32767
谁能解释为什么在函数调用改变输出之前打印一些东西?