我理解this在lambda中捕获(修改对象属性)的正确方法如下:
auto f = [this] () { /* ... */ };
Run Code Online (Sandbox Code Playgroud)
但我很好奇我所看到的以下特点:
class C {
public:
void foo() {
// auto f = [] () { // this not captured
auto f = [&] () { // why does this work?
// auto f = [&this] () { // Expected ',' before 'this'
// auto f = [this] () { // works as expected
x = 5;
};
f();
}
private:
int x;
};
Run Code Online (Sandbox Code Playgroud)
我很困惑的奇怪(并希望得到回答)是以下工作的原因:
auto f = …Run Code Online (Sandbox Code Playgroud)