andreasfertig / cppinsights

C++ Insights - See your source code with the eyes of a compiler
https://cppinsights.io
MIT License
4.08k stars 240 forks source link

Lambda Capture Variable Not Used in Generated Code #640

Closed glucu closed 4 months ago

glucu commented 5 months ago

Issue: The generated code for a lambda function that captures a variable by value does not use the captured variable in the lambda body.

Example Code:

int main()
{
    int z{5};
    auto sum = [z](int x, int y){ return x + y + z; };
}

Generated Code

int main()
{
  int z = {5};

  class __lambda_7_16
  {
    public: 
    inline /*constexpr */ int operator()(int x, int y) const
    {
      return (x + y) + x;
    }

    private: 
    int z;

    public:
    __lambda_7_16(int & _z)
    : z{_z}
    {}

  };

  __lambda_7_16 sum = __lambda_7_16{z};
  return 0;
}

Expected Generated Code

int main()
{
  int z = {5};

  class __lambda_7_16
  {
    public: 
    inline /*constexpr */ int operator()(int x, int y) const
    {
      return (x + y) + z; // Correct: `z` is used here 
    }

    private: 
    int z;

    public:
    __lambda_7_16(int & _z)
    : z{_z}
    {}

  };

  __lambda_7_16 sum = __lambda_7_16{z};
  return 0;
}

Note The issue seems to be intermittent, and it may not reproduce consistently.

andreasfertig commented 5 months ago

Hello @glucu,

thanks for reporting this issue! After a couple of days and tries, I was not able to reproduce it. Are you running a self-build version?

Andreas

glucu commented 5 months ago

Hi @andreasfertig

I also tested further and was unable to reproduce the problem. Odd. This was run on cppinsights.io.