Consider the following code:
int main() {
int n = 0;
return [n] { return n; }(); // ok
}
According to https://cppinsights.io, the code above will be translated into the following code:
int main() {
int n = 0;
class __lambda_3_12 {
public:
inline /*constexpr */ int operator()() const {
return n;
}
private:
int n;
public:
__lambda_3_12(int& _n) : n{_n} {
}
} __lambda_3_12{n};
return __lambda_3_12.operator()();
}
However, the following code is ill-formed:
int main() {
int n = 0;
// error: invalid use of 'this' outside of a non-static member function
return [n] { return this->n; }();
}
I think the C++ standard must have forbidden the compiler to use this pointer to access the captured variables. However, I cannot find the exact statements in 7.5.6 [expr.prim.lambda] of the C++ standard draft.
thisbecause a lambda isn't really a class or object in itself, from the C++ language perspective. There is no context in the lambda except the captures you have.this, what wouldthisthen refer to? The compiler-generated class object, or the capturedthis?[n](this auto& self) { return self.n; }.[n](this auto& self) { return self.n; }is ill-formed, either.