下面的lambda函数捕获this
(因此bar()
可以访问其实例变量)和局部变量a,b,c
。
class Foo
{
int x, y, z;
std::function<void(void)> _func;
// ...
void bar()
{
int a, b, c;
// ...
_func = [this, a, b, c]() // lambda func
{
int u = this->x + a;
// ...
};
}
};
但是,如果我想捕获许多实例变量,并希望避免在捕获列表中明确命名它们,我做到了[[not似乎可以做到这一点:
_func = [this, =]() // lambda func
{
// ...
};
我在=
之后的this,
处遇到编译器错误:
error: expected variable name or 'this' in lambda capture list
如果我尝试这个
_func = [=,this]() // lambda func { // ... };
我知道
error: 'this' cannot be explicitly captured when the capture default is '='
是否存在用于按值捕获this
和其他所有内容的捷径?
[=]通过副本捕获lambda主体中使用的所有自动变量,并通过引用捕获当前对象使用的所有自动变量
[=]
已按值捕获this
。看一下下面的实时代码:http://cpp.sh/87iw6#include <iostream>
#include <string>
struct A {
std::string text;
auto printer() {
return [=]() {
std::cout << this->text << "\n";
};
}
};
int main() {
A a;
auto printer = a.printer();
a.text = "Hello, world!";
printer();
}
[=]
将起作用,因为它会通过复制捕获lambda主体中使用的所有自动变量。