C++ Lambdas

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


  • [default-capture, capture-list] (argument-list) mutable throw-specification attributes -> return-type { lambda-body } // Order of lambda specifiers and attributes.
  • [capture-list] (argument-list) { lambda-body } // Common lambda definition.
  • [=] (argument-list) { lambda-body } // Captures all needed local variables by value.
  • [&] (argument-list) { lambda-body } // Captures all needed local variables by reference.
  • [capture-list] { lambda-body } // Argument list and specifiers can be omitted.


default-captureSpecifies how all non-listed variables are captured. Can be = (capture by value) or & (capture by reference). If omitted, non-listed variables are inaccessible within the lambda-body. The default-capture must precede the capture-list.
capture-listSpecifies how local variables are made accessible within the lambda-body. Variables without prefix are captured by value. Variables prefixed with & are captured by reference. Within a class method, this can be used to make all its members accessible by reference. Non-listed variables are inaccessible, unless the list is preceded by a default-capture.
argument-listSpecifies the arguments of the lambda function.
mutable(optional) Normally variables captured by value are const. Specifying mutable makes them non-const. Changes to those variables are retained between calls.
throw-specification(optional) Specifies the exception throwing behavior of the lambda function. For example: noexcept or throw(std::exception).
attributes(optional) Any attributes for the lambda function. For example, if the lambda-body always throws an exception then [[noreturn]] can be used.
-> return-type(optional) Specifies the return type of the lambda function. Required when the return type cannot be determined by the compiler.
lambda-bodyA code block containing the implementation of the lambda function.


C++17 (the current draft) introduces constexpr lambdas, basically lambdas that can be evaluated at compile time. A lambda is automatically constexpr if it satisfies constexpr requirements, but you can also specify it using the constexpr keyword:

//Explicitly define this lambdas as constexpr
[]() constexpr {
    //Do stuff

Got any C++ Question?