#include <iostream>
int foo(int x = [](){ static int x = 0; return ++x; }()) {
return x;
};
int main() {
std::cout << foo() << foo(); // prints "12", not "11"
}
I know that default arguments are evaluated each time a function is called. Does that mean that the lambda type is different on each call? Please point to the standard quotes explaining the behaviour here.
This example from dcl.fct.default makes pretty clear that the intent is that the point where the default argument is defined also defines the semantics:
int a = 1;
int f(int);
int g(int x = f(a)); // default argument: f(::a)
void h() {
a = 2;
{
int a = 3;
g(); // g(f(::a))
}
}
In particular, the default argument is not just a token sequence that is inserted at the point of the function call and then analysed.
Following this intent, the lambda expression is analysed at the point of definition of the default argument, not at the point of function call. Therefore, there is only one lambda type, not many, and the correct result is 12
.
The Standard doesn't express this clearly enough with regards to lambda expressions being used as default arguments, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With