[expr.prim.lambda] (original) (raw)

7 Expressions [expr]

7.5 Primary expressions [expr.prim]

7.5.5 Lambda expressions [expr.prim.lambda]

7.5.5.1 General [expr.prim.lambda.general]

A lambda-expression provides a concise way to create a simple function object.

[Example 1: #include <algorithm> #include <cmath> void abssort(float* x, unsigned N) { std::sort(x, x + N, [](float a, float b) { return std::abs(a) < std::abs(b); });} — _end example_]

A lambda-expression is a prvalue whose result object is called the closure object.

If a lambda-expression does not include alambda-declarator, it is as if the lambda-declarator were().

The lambda return type is auto, which is replaced by the type specified by thetrailing-return-type if provided and/or deduced fromreturn statements as described in [dcl.spec.auto].

[Example 2: auto x1 = [](int i){ return i; }; auto x2 = []{ return { 1, 2 }; }; int j;auto x3 = []()->auto&& { return j; }; — _end example_]

[Example 3: int i = [](int i, auto a) { return i; }(3, 4); int j = []<class T>(T t, int i) { return i; }(3, 4); — _end example_]

7.5.5.2 Closure types [expr.prim.lambda.closure]

The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.

The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the correspondinglambda-expression.

[Note 1:

This determines the set of namespaces and classes associated with the closure type ([basic.lookup.argdep]).

The parameter types of a lambda-declarator do not affect these associated namespaces and classes.

— _end note_]

The closure type is not an aggregate type.

An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

An implementation shall not add members of rvalue reference type to the closure type.

[Note 2:

The function call operator template for a generic lambda might be an abbreviated function template ([dcl.fct]).

— _end note_]

[Example 1: auto glambda = [](auto a, auto&& b) { return a < b; };bool b = glambda(3, 3.14); auto vglambda = [](auto printer) { return [=](auto&& ... ts) { printer(std::forward<decltype(ts)>(ts)...);return [=]() { printer(ts ...);};};};auto p = vglambda( [](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; } );auto q = p(1, 'a', 3.14); q(); — _end example_]

It is neither virtual nor declared volatile.

Anynoexcept-specifier specified on a lambda-expressionapplies to the corresponding function call operator or operator template.

An attribute-specifier-seq in a lambda-declarator appertains to the type of the corresponding function call operator or operator template.

The function call operator or any given operator template specialization is a constexpr function if either the corresponding lambda-expression'sparameter-declaration-clauseis followed by constexpr or consteval, or it satisfies the requirements for a constexpr function ([dcl.constexpr]).

[Note 3:

Names referenced in the lambda-declarator are looked up in the context in which thelambda-expression appears.

— _end note_]

[Example 2: auto ID = [](auto a) { return a; };static_assert(ID(3) == 3); struct NonLiteral { NonLiteral(int n) : n(n) { } int n;};static_assert(ID(NonLiteral{3}).n == 3); — _end example_]

[Example 3: auto monoid = [](auto v) { return [=] { return v; }; };auto add = [](auto m1) constexpr { auto ret = m1();return [=](auto m2) mutable { auto m1val = m1();auto plus = [=](auto m2val) mutable constexpr { return m1val += m2val; }; ret = plus(m2());return monoid(ret);};};constexpr auto zero = monoid(0);constexpr auto one = monoid(1);static_assert(add(one)(zero)() == one()); auto two = monoid(2); assert(two() == 2); static_assert(add(one)(one)() == two()); static_assert(add(one)(one)() == monoid(2)()); — _end example_]

[Note 4:

[Example 4: template <typename T> concept C1 = ;template <std::size_t N> concept C2 = ;template <typename A, typename B> concept C3 = ;auto f = []<typename T1, C1 T2> requires C2<sizeof(T1) + sizeof(T2)> (T1 a1, T1 b1, T2 a2, auto a3, auto a4) requires C3<decltype(a4), T2> { }; — _end example_]

— _end note_]

The closure type for a non-generic lambda-expression with nolambda-capturewhose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator.

The conversion is to “pointer to noexcept function” if the function call operator has a non-throwing exception specification.

The value returned by this conversion function is the address of a function F that, when invoked, has the same effect as invoking the closure type's function call operator on a default-constructed instance of the closure type.

F is a constexpr function if the function call operator is a constexpr function and is an immediate function if the function call operator is an immediate function.

For a generic lambda with no lambda-capture, the closure type has a conversion function template to pointer to function.

The conversion function template has the same invented template parameter list, and the pointer to function has the same parameter types, as the function call operator template.

The return type of the pointer to function shall behave as if it were adecltype-specifier denoting the return type of the corresponding function call operator template specialization.

[Note 5:

If the generic lambda has no trailing-return-type or the trailing-return-type contains a placeholder type, return type deduction of the corresponding function call operator template specialization has to be done.

The corresponding specialization is that instantiation of the function call operator template with the same template arguments as those deduced for the conversion function template.

Consider the following:auto glambda = [](auto a) { return a; };int (*fp)(int) = glambda;

The behavior of the conversion function of glambda above is like that of the following conversion function:struct Closure { template<class T> auto operator()(T t) const { } template<class T> static auto lambda_call_operator_invoker(T a) { } template<class T> using fptr_t = decltype(lambda_call_operator_invoker(declval<T>())) (*)(T);template<class T> operator fptr_t<T>() const { return &lambda_call_operator_invoker; } };

— _end note_]

[Example 5: void f1(int (*)(int)) { } void f2(char (*)(int)) { } void g(int (*)(int)) { } void g(char (*)(char)) { } void h(int (*)(int)) { } void h(char (*)(int)) { } auto glambda = [](auto a) { return a; }; f1(glambda); f2(glambda); g(glambda); h(glambda); int& (*fpi)(int*) = [](auto* a) -> auto& { return *a; }; — _end example_]

The value returned by any given specialization of this conversion function template is the address of a function F that, when invoked, has the same effect as invoking the generic lambda's corresponding function call operator template specialization on a default-constructed instance of the closure type.

F is a constexpr function if the corresponding specialization is a constexpr function andF is an immediate function if the function call operator template specialization is an immediate function.

[Note 6:

This will result in the implicit instantiation of the generic lambda's body.

The instantiated generic lambda's return type and parameter types are required to match the return type and parameter types of the pointer to function.

— _end note_]

[Example 6: auto GL = [](auto a) { std::cout << a; return a; };int (*GL_int)(int) = GL; GL_int(3); — _end example_]

The conversion function or conversion function template is public, constexpr, non-virtual, non-explicit, const, and has a non-throwing exception specification.

[Example 7: auto Fwd = [](int (*fp)(int), auto a) { return fp(a); };auto C = [](auto a) { return a; };static_assert(Fwd(C,3) == 3); auto NC = [](auto a) { static int s; return a; };static_assert(Fwd(NC,3) == 3); — _end example_]

[Example 8: struct S1 { int x, y;int operator()(int);void f() { [=]()->int { return operator()(this->x + y); };} }; — _end example_]

The closure type associated with a lambda-expression has no default constructor if the lambda-expression has a lambda-captureand a defaulted default constructor otherwise.

It has a defaulted copy constructor and a defaulted move constructor ([class.copy.ctor]).

It has a deleted copy assignment operator if the lambda-expressionhas a lambda-capture and defaulted copy and move assignment operators otherwise ([class.copy.assign]).

[Note 7:

These special member functions are implicitly defined as usual, and might therefore be defined as deleted.

— _end note_]

The closure type associated with a lambda-expression has an implicitly-declared destructor ([class.dtor]).

7.5.5.3 Captures [expr.prim.lambda.capture]

The body of a lambda-expression may refer to local entities of enclosing block scopes by capturing those entities, as described below.

If a lambda-capture includes a capture-default that is &, no identifier in a simple-capture of thatlambda-capture shall be preceded by &.

If a lambda-capture includes acapture-default that is =, eachsimple-capture of that lambda-capture shall be of the form “& identifier ...”, “this”, or “* this”.

[Note 1:

The form [&,this] is redundant but accepted for compatibility with ISO C++ 2014.

— _end note_]

Ignoring appearances ininitializers of init-captures, an identifier orthis shall not appear more than once in alambda-capture.

[Example 1: struct S2 { void f(int i); };void S2::f(int i) { [&, i]{ }; [&, this, i]{ }; [&, &i]{ }; [=, *this]{ }; [=, this]{ }; [i, i]{ }; [this, *this]{ }; } — _end example_]

A lambda-expression shall not have a capture-default or simple-capturein its lambda-introducerunless its innermost enclosing scope is a block scope ([basic.scope.block]) or it appears within a default member initializer and its innermost enclosing scope is the corresponding class scope ([basic.scope.class]).

The simple-captures this and * thisdenote the local entity *this.

An entity that is designated by asimple-captureis said to be explicitly captured.

[Example 2: void f() { int x = 0;auto g = [x](int x) { return 0; }; } — _end example_]

An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression'scompound-statement, except that:

[Note 2:

This enables an init-capture like “x = std​::​move(x)”; the second “x” must bind to a declaration in the surrounding context.

— _end note_]

[Example 3: int x = 4;auto y = [&r = x, x = x+1]()->int { r += 2;return x+2;}(); auto z = [a = 42](int a) { return 1; }; — _end example_]

For the purposes of lambda capture, an expression potentially references local entities as follows:

If an expression potentially references a local entity within a declarative region in which it is odr-usable, and the expression would be potentially evaluated if the effect of any enclosing typeid expressions ([expr.typeid]) were ignored, the entity is said to be implicitly capturedby each intervening lambda-expression with an associatedcapture-default that does not explicitly capture it.

The implicit capture of *this is deprecated when thecapture-default is =; see [depr.capture.this].

[Example 4: void f(int, const int (&)[2] = {}); void f(const int&, const int (&)[1]); void test() { const int x = 17;auto g = [](auto a) { f(x); };auto g1 = [=](auto a) { f(x); };auto g2 = [=](auto a) { int selector[sizeof(a) == 1 ? 1 : 2]{}; f(x, selector); };auto g3 = [=](auto a) { typeid(a + x); };}

Within g1, an implementation might optimize away the capture of x as it is not odr-used.

— _end example_]

[Note 4:

The set of captured entities is determined syntactically, and entities might be implicitly captured even if the expression denoting a local entity is within a discarded statement ([stmt.if]).

[Example 5: template<bool B> void f(int n) { [=](auto a) { if constexpr (B && sizeof(a) > 4) { (void)n; } }(0);} — _end example_]

— _end note_]

An entity is captured if it is captured explicitly or implicitly.

An entity captured by a lambda-expression is odr-used ([basic.def.odr]) in the scope containing the lambda-expression.

[Note 5:

As a consequence, if a lambda-expressionexplicitly captures an entity that is not odr-usable, the program is ill-formed ([basic.def.odr]).

— _end note_]

[Example 6: void f1(int i) { int const N = 20;auto m1 = [=]{ int const M = 30;auto m2 = [i]{ int x[N][M]; x[0][0] = i; };};struct s1 { int f;void work(int n) { int m = n*n;int j = 40;auto m3 = [this,m] { auto m4 = [&,j] { int x = n; x += m; x += i; x += f; };};} };} struct s2 { double ohseven = .007;auto f() { return [this] { return [*this] { return ohseven; };}();} auto g() { return [] { return [*this] { }; }();} }; — _end example_]

[Note 6:

Because local entities are not odr-usable within a default argument ([basic.def.odr]), a lambda-expression appearing in a default argument cannot implicitly or explicitly capture any local entity.

Such a lambda-expressioncan still have an init-capture if any full-expression in its initializersatisfies the constraints of an expression appearing in a default argument ([dcl.fct.default]).

— _end note_]

[Example 7: void f2() { int i = 1;void g1(int = ([i]{ return i; })()); void g2(int = ([i]{ return 0; })()); void g3(int = ([=]{ return i; })()); void g4(int = ([=]{ return 0; })()); void g5(int = ([]{ return sizeof i; })()); void g6(int = ([x=1]{ return x; })()); void g7(int = ([x=i]{ return x; })()); } — _end example_]

An entity is captured by copy if

For each entity captured by copy, an unnamed non-static data member is declared in the closure type.

The declaration order of these members is unspecified.

The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise.

A member of an anonymous union shall not be captured by copy.

Every id-expression within the compound-statement of alambda-expression that is an odr-use of an entity captured by copy is transformed into an access to the corresponding unnamed data member of the closure type.

[Note 7:

An id-expression that is not an odr-use refers to the original entity, never to a member of the closure type.

However, such an id-expression can still cause the implicit capture of the entity.

— _end note_]

If *this is captured by copy, each expression that odr-uses *this is transformed to instead refer to the corresponding unnamed data member of the closure type.

[Example 8: void f(const int*);void g() { const int N = 10;[=] { int arr[N]; f(&N); };} — _end example_]

An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy.

It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.

If declared, such non-static data members shall be of literal type.

[Example 9: static_assert([](int n) { return [&n] { return ++n; }(); }(3) == 4); — _end example_]

A bit-field or a member of an anonymous union shall not be captured by reference.

An id-expression within the compound-statement of a lambda-expressionthat is an odr-use of a reference captured by reference refers to the entity to which the captured reference is bound and not to the captured reference.

[Note 8:

The validity of such captures is determined by the lifetime of the object to which the reference refers, not by the lifetime of the reference itself.

— _end note_]

[Example 10: auto h(int &r) { return [&] { ++r; };} — _end example_]

If a lambda-expression m2 captures an entity and that entity is captured by an immediately enclosing lambda-expression m1, thenm2's capture is transformed as follows:

[Example 11:

The nested lambda-expressions and invocations below will output123234.

int a = 1, b = 1, c = 1;auto m1 = [a, &b, &c]() mutable { auto m2 = [a, b, &c]() mutable { std::cout << a << b << c; a = 4; b = 4; c = 4;}; a = 3; b = 3; c = 3; m2();}; a = 2; b = 2; c = 2; m1(); std::cout << a << b << c; — _end example_]

When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object, and the non-static data members corresponding to theinit-captures are initialized as indicated by the correspondinginitializer (which may be copy- or direct-initialization).

(For array members, the array elements are direct-initialized in increasing subscript order.)

These initializations are performed in the (unspecified) order in which the non-static data members are declared.

[Note 9:

This ensures that the destructions will occur in the reverse order of the constructions.

— _end note_]

[Note 10:

If a non-reference entity is implicitly or explicitly captured by reference, invoking the function call operator of the corresponding lambda-expressionafter the lifetime of the entity has ended is likely to result in undefined behavior.

— _end note_]

An init-capture containing an ellipsis is a pack expansion that introduces aninit-capture pack ([temp.variadic]) whose declarative region is the lambda-expression's compound-statement.

[Example 12: template<class... Args> void f(Args... args) { auto lm = [&, args...] { return g(args...); }; lm();auto lm2 = [...xs=std::move(args)] { return g(xs...); }; lm2();} — _end example_]