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


1568. Temporary lifetime extension with intervening cast

Section: 6.7.7  [class.temporary]     Status: dup     Submitter: Steve Adamczyk     Date: 2012-10-11

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.)

Rationale (April, 2013):

This issue is a duplicate of issue 1376.