Skip to content

static inside lambda results in incorrect code #467

@JJCUBER

Description

@JJCUBER

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)();

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions