C++ lambda 表达式传递的变量默认不可变
我遇到例如以下问题:
int count=0; listener->onTouchMoved=[count](Touch* t,Event* e){ count++; log("onTouchMoved"); };
Xcode下的编译错误为:Cannot assign to a variable captured by copy in a non-mutable lambda.
那么怎样解决呢?
在 lambda表达式中。捕获的变量默认是不可变的。
This function call operator or operator template is declared const (9.3.1) if and only if the lambda-expression’s parameter-declaration-clause is not followed by mutable.
因此假设你想再在ambda表达式内改变变量的值,那么就要改写以上内容为:
int count=0; listener->onTouchMoved=[count](Touch* t,Event* e) mutable{ count++; log("onTouchMoved"); };