使用值捕获不可以在表达式内修改值,但是使用Mutable关键字可以打破这一规则 但是即使在lambda表达式内修改了值, 在作用域外, 值也不会呗改变
下面这段例子输出的是
Inside
Outside
#include <memory>
#include <iostream>
#include <stdio.h>
#include <functional>
struct Mystruct
{
Mystruct(){
std::cout << "construct\n";
}
~Mystruct(){
std::cout << "destory\n";
}
std::string str;
};
void testFoo()
{
std::cout << "TestFoo\n";
}
int main()
{
Mystruct s;
s.str = "outside";
auto func = [s]() mutable {
s.str = "inside";
(*testFoo)();
std::cout << s.str << std::endl;
};
// Report Error -- cannot be modified
// auto func = [s]() -> void {
// s.str = "inside";
// (*testFoo)();
// std::cout << s.str << std::endl;
// };
func();
std::cout << s.str << std::endl;
getchar();
}