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

2024-11-11


2737. Temporary lifetime extension for reference init-captures

Section: 7.5.6.3  [expr.prim.lambda.capture]     Status: review     Submitter: Tomasz Kamiński     Date: 2023-05-23

Consider:

  struct S {};
  const S f();
  auto x = [&ref = f()] { return ref; }

Subclause 7.5.6.3 [expr.prim.lambda.capture] paragraph 6 specifies:

An init-capture inhabits the lambda scope (6.4.5 [basic.scope.lambda]) of the lambda-expression. An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;”, except that:

It is unclear whether the temporary returned by f() is lifetime-extended by being bound to a reference init-capture.

There is implementation divergence: gcc rejects the example; clang accepts and extends the lifetime of the temporary; MSVC and EDG accept and do not extend the lifetime.

Proposed resolution (reviewed by CWG 2024-03-01):

Change in 7.5.6.3 [expr.prim.lambda.capture] paragraph 6 as follows:

An init-capture inhabits the lambda scope (6.4.5 [basic.scope.lambda]) of the lambda-expression. An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;”, except that: