Search code examples
c++lambdaclosuresc++14default-constructor

Why closure types / lambdas have no default constructor in C++


What is the reason why lambdas have no default constructor? Is there any technical reason behind that, or is it a pure design decision?


Solution

  • Lambdas in C++ are a syntactic convenience to allow the programmer to avoid declaring a functor using traditional syntax like

    struct my_functor
    {
    bool operator()(Object &) { /* do something */ return false; }
    }
    

    because writing functors using this syntax is considered too long winded for simple functions.

    Lambdas offer parameter capture options e.g [=], [&] etc. , to save you declaring variables and initializing them, like you might do in the constructor of a functor object.

    So Lambdas don't expose any constructor syntax to you by design.

    There is no technical reason a lambda function could not expose a constructor, however if it were to do so it would stop mimicking the design concept it is named for.


    With thanks to the commentators under the question.