Title
Temporary lifetime extension with intervening cast
Status
dup
Section
6.7.7 [class.temporary]
Submitter
Steve Adamczyk

Created on 2012-10-11.00:00:00 last changed 140 months ago

Messages

Date: 2013-04-15.00:00:00

Rationale (April, 2013):

This issue is a duplicate of issue 1376.

Date: 2022-11-20.07:54:16

According to 6.7.7 [class.temporary] paragraphs 4-5,

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression...

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference...

It is not clear whether this applies to an example like the following:

  struct S { };
  const S& r = (const S&)S();

In one sense r is being bound to the temporary because the object to which r refers is the temporary object. From another perspective, however, r is being bound not to a temporary but to the lvalue expression (const S&)S(), or, more precisely, to the invented temporary variable described in 7.6.1.9 [expr.static.cast] paragraph 4:

Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (9.4 [dcl.init]). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

(Since the invented variable t is called a “temporary,” perhaps the intent is that its lifetime is extended to that of r, and then the lifetime of the S() temporary would be that of t. However, this reasoning is tenuous, and it may be better to make the intent explicitly clear.)

(See also issue 1299.)

History
Date User Action Args
2013-05-03 00:00:00adminsetmessages: + msg4445
2013-05-03 00:00:00adminsetstatus: open -> dup
2012-10-11 00:00:00admincreate