在以下示例中,捕获列表中使用[this]与捕获列表中使用捕获引用[&]相反,如图所示,有什么区别?我已经试过并且他们产生相同的输出。当在类中使用时,lambda捕获列表中的[this]和[&]是否等效?
#include <iostream>
class Test {
public:
int x = 2;
void test1(void) { std::cout << "test1" << std::endl; };
void test_lambda(void) {
auto lambda = [&]() {
std::cout << "x: " << x << " y: " << y << " z: " << z << std::endl;
this->test1();
};
lambda();
}
protected:
int y = 3;
private:
int z = 4;
};
int main() {
Test t;
t.test_lambda();
}
在C++编程语言,Stroustrop说:
Members are always captured by reference. That is, [this] implies that members are accessed through this rather than copied into the lambda.
这似乎在暗示,他们可能意味着同样的事情。如果是这样的话,为什么我们需要[这个]?
&可用于特定变量 –
始终使用您可以使用的最不强大的捕获。这不仅让当地的推理更容易,但你也可能在一段时间避免出错一次 – KABoissonneault