I have a small "lambda expression" in the below function:
int main()
{
int x = 10;
auto lambda = [=] () { return x + 3; };
}
Below is the "anonymous closure class" generated for the above lambda expression.
int main()
{
int x = 10;
class __lambda_3_19
{
public: inline /*constexpr */ int operator()() const
{
return x + 3;
}
private:
int x;
public: __lambda_3_19(int _x) : x{_x}
{}
};
__lambda_3_19 lambda = __lambda_3_19{x};
}
The closure's "operator()" generated by the compiler is implicitly const. Why did the standard committee make it const
by default?
__lambda_3_19
is UB. Would you mind changing the token name to keep the UB pedants away>? – Varickconst
though? why would it limit the use of your lambda on purpose? – Cummerbundoperator()
function is marked asconst
then that's not possible. – Jewellconst
and non-const is the default. Its weird that we are used to redundantly repeat the return type of a function whenauto
return types could be natural. In some sense lambdas give you a glimpse of how c++ could look like if it was reinvented from scratch today. – Archiemutable
will result in a clear compiler error, while a missingconst
is an error that usually the compiler cannot diagnose – Archie