Title
Lifetime extension of temporaries past function return
Status
open
Section
6.8.7 [class.temporary]
Submitter
Hubert Tong

Created on 2025-09-12.00:00:00 last changed yesterday

Messages

Date: 2025-09-12.22:42:26

Suggested resolution:

Add in 6.8.7 [class.temporary] bullet 6.11 as follows:

  • ...
  • A temporary object bound to a reference element of an aggregate of class type initialized from a parenthesized expression-list (9.5 [dcl.init]) persists until the completion of the full-expression containing the expression-list.
  • The lifetime of a temporary bound to a reference member of the returned value in a function return statement (8.8.4 [stmt.return]) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
  • A temporary bound to a reference in a new-initializer (7.6.2.8 [expr.new]) persists until ...
Date: 2025-09-12.00:00:00

(From submission #760.)

Consider:

  struct B { ~B(); };
  struct A { const B &b; };
  A foo() { return {{}}; }   // #1
  void bar();
  int main() {
    A a = foo();
    bar();
  }

At #1, a temporary of type B is created and, due to guaranteed copy elision, is bound to a.b in main. The current rules, as amended by P2748R5 (Disallow Binding a Returned Glvalue to a Temporary), prescribe lifetime extension of that temporary, which is a novel requirement accidentally imposed by P2748R5 that is hard to implement.

History
Date User Action Args
2025-09-12 22:42:26adminsetmessages: + msg8096
2025-09-12 00:00:00admincreate