Search code examples
c++c++11lambdaconstants

What does const lambda mean?


#include <iostream>
int foo(int i)
{
    const auto a = [&i](){ i = 7; };
    a();
    return i;
}
int main()
{
    std::cout << foo(42) << std::endl;
    return 0;
}

This compiles( g++ -std=c++11 -Wall -Wextra -Wpedantic main.cpp ) and prints 7. Which is surprising to me, because by declaring a to be a constant object, I would have expected i to be referenced as const int&. It clearly isn't, why?


Solution

  • Lambdas are just like non-lambdas, except their implementation details are hidden. Therefore, it may be easier to explain using a non-lambda functor:

    #include <iostream>
    int foo(int i)
    {
        struct F {
          int &i;
          int operator()() const { i = 7; return i * i; }
        };
        const F a {i};
        a();
        return i;
    }
    int main()
    {
        std::cout << foo(42) << std::endl;
        return 0;
    }
    

    F has a int & reference member i. const F cannot have its instance data modified, but a modification to i isn't a modification to its instance data. A modification to its instance data would be re-binding i to another object (which isn't allowed anyway).