【发布时间】:2018-05-04 21:39:06
【问题描述】:
下面的 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 和其他所有内容的简写?
更新: [=, this] 作为 lambda 捕获是 new feature of C++20
【问题讨论】:
-
[=]也不能捕获this吗? -
真的吗?天哪,它确实如此。我想我会删除我的问题。
-
我想 SO 希望我把这个问题留在这里......也许其他一些糟糕的编程灵魂(例如,曾经使用
[unowned self]的 Swift 程序员)会发现它很有用。 -
[this,=] 将是一个令人困惑的矛盾修饰法,因为这是一个指向对象的指针..所以实际上您将通过引用捕获整个对象,这与值 [=] 的默认值冲突。