[英]C++11 lambda capture `this` and capture local variables by value
下面的 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;
// ...
};
}
};
但是,如果我想捕捉许多实例变量,并希望避免明确的捕获列表命名它们,我似乎并没有能够做到这一点:
_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
和其他所有内容的简写?
正如 cppreference 所说:
[=] 通过复制捕获 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 主体中使用的所有自动变量。
这是示例输出: https : //www.ideone.com/kkXvJT
#include <iostream>
#include <functional>
class Foo
{
int x, y, z;
std::function<void(void)> _func;
public:
Foo(int a): x(a), y(0), z(0) {}
void bar()
{
int a = 1,b,c;
_func = [=]()
{
int u = this->x + a;
std::cout << u << std::endl;
};
_func(); // lambda call
}
};
int main()
{
Foo obj(1);
obj.bar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.