Title
Lifetime extension through static_cast
Status
open
Section
6.7.7 [class.temporary]
Submitter
Brian Bi

Created on 2022-10-17.00:00:00 last changed 8 months ago

Messages

Date: 2023-07-28.20:24:53

Suggested resolution:

Change in 6.7.7 [class.temporary] bullet 6.6 as follows:

  • ...
  • a converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof, where
    • the cast does not invoke a user-defined conversion, or
    • the cast invokes a user-defined conversion that yields a prvalue, and the glvalue result of the cast is bound directly (9.4.4 [dcl.init.ref]) to that prvalue,
  • ...
Date: 2023-07-29.06:03:52

Consider:

  struct S { S(int) {} };

  const S& r1 = 0; // #1
  const S& r2 = static_cast<const S&>(S(0)); // #2
  const S& r3 = static_cast<const S&>(0); // #3
  // Are r1, r2, and r3 dangling past this point?

For #1, a temporary object is materialized and the reference binds to the result of the materialization conversion. This results in lifetime extension per 6.7.7 [class.temporary] bullet 6.1.

For #2, 6.7.7 [class.temporary] bullet 6.6 requires the cast to convert "without a user-defined conversion", but S(0) is such.

For #3, a user-defined conversion is clearly required.

However, implementations treat all three cases the same and do extend the lifetime of the temporary.

History
Date User Action Args
2023-07-28 20:24:53adminsetmessages: + msg7388
2022-10-17 00:00:00admincreate