This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 113d. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-03-20


764. Capturing unused variables in a lambda expression

Section: 7.5.5.3  [expr.prim.lambda.capture]     Status: CD2     Submitter: Steve Adamczyk     Date: 6 February, 2009

[Voted into the WP at the July, 2009 meeting as part of N2927.]

7.5.5 [expr.prim.lambda] paragraph 5 says,

The compound-statement of a lambda expression shall use (6.3 [basic.def.odr]) an automatic variable or reference from the context where the lambda expression appears only if the name of the variable or reference is a member of the effective capture set...

The reference to 6.3 [basic.def.odr] makes clear that the technical meaning of “use” is in view here, and that the names of variables can appear without being captured if they are constants used as values or if they are unevaluated operands.

There appears to be a disconnect with the preceding paragraph, however, in the description of which variables are implicitly captured by a capture-default:

for each name v that appears in the lambda expression and denotes a local variable or reference with automatic storage duration in the context where the lambda expression appears and that does not appear in the capture-list or as a parameter name in the lambda-parameter-declaration-list...

It would be more consistent if only variables that were required by paragraph 5 to be captured were implicitly captured, i.e., if “that appears in the lambda expression” were replaced by “that is used (6.3 [basic.def.odr]) in the compound-statement of the lambda expression.” For example,

    struct A {
      A();
      A(const A&);
      ~A();
    };
    void f() {
      A a;
      int i = [=]() { return sizeof a; }();
    }

Here, a will be captured (and copied), even though it is not “used” in the lambda expression.

Proposed resolution (July, 2009)

See document PL22.16/09-0117 = WG21 N2927.