The code
#include <iostream>
int main()
{
auto l = []()
{
static int n{};
std::cout << ++n;
};
}
generates code with two separate functions with the same static variable declared twice
#include <iostream>
int main()
{
class __lambda_5_11
{
public:
inline void operator()() const
{
static int n = {};
std::cout.operator<<(++n);
}
using retType_5_11 = void (*)();
inline /*constexpr */ operator retType_5_11 () const noexcept
{
return __invoke;
};
private:
static inline void __invoke()
{
static int n = {};
std::cout.operator<<(++n);
}
public:
// /*constexpr */ __lambda_5_11() = default;
};
__lambda_5_11 l = __lambda_5_11{};
return 0;
}
If one were to run the generated code with some direct calls of the lambda and some calls of it through a function pointer, it would result in incorrect results.
For example, you would get 123412 if you called it 4 times directly and then 2 times through a function pointer when using the generated code from cppinsights (whereas the original lambda would print 123456):
l();
l();
l();
l();
(+l)();
(+l)();
The code
generates code with two separate functions with the same static variable declared twice
If one were to run the generated code with some direct calls of the lambda and some calls of it through a function pointer, it would result in incorrect results.
For example, you would get
123412if you called it 4 times directly and then 2 times through a function pointer when using the generated code from cppinsights (whereas the original lambda would print123456):