Movatterモバイル変換


[0]ホーム

URL:


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

2025-12-20


427.static_cast ambiguity: conversion versus cast to derived

Section:7.6.1.9  [expr.static.cast]    Status:CD1    Submitter:Mark Mitchell    Date:5 July 2003

[Voted into WP at October 2004 meeting.]

Consider this code:

  struct B {};  struct D : public B {    D(const B&);  };  extern B& b;  void f() {    static_cast<const D&>(b);  }

The rules forstatic_cast permit the conversion to"const D&" in two ways:

  1. D is derived from B, and b is an lvalue, so a cast to D& is OK.
  2. const D& t = b is valid, using the constructor for D. [Ed. note:actually, this should be parenthesized initialization.]

The first alternative is 7.6.1.9 [expr.static.cast]/5; the second is7.6.1.9 [expr.static.cast]/2.

Presumably the first alternative is better -- it's the "simpler"conversion. The standard does not seem to make that clear.

Steve Adamczyk:I take the "Otherwise" at the beginning of7.6.1.9 [expr.static.cast]/3 as meaning thatthe paragraph 2 interpretation is used if available, which means inyour example above interpretation 2 would be used. However, that'snot what EDG's compiler does, and I agree that it's not the "simpler"conversion.

Proposed Resolution (October 2003):

Move paragraph 5.2.9/5:

An lvalue of type``cv1B'',whereBis a class type, can be cast to type ``reference tocv2D'',whereDis a class derived (11.7 [class.derived]) fromB,if a valid standard conversion from ``pointer toD''to ``pointer toB''exists (7.3.12 [conv.ptr]),cv2is the same cv-qualification as, or greater cv-qualification than,cv1,andBis not a virtual base class ofD.The result is an lvalue of type``cv2D.''If the lvalue of type``cv1B''is actually a sub-object of an object of typeD,the lvalue refers to the enclosing object of typeD.Otherwise, the result of the cast is undefined.[Example:

  struct B {};  struct D : public B {};  D d;  B &br = d;  static_cast<D&>(br);            //  produces lvalue to the originald  object
--- end example]

before paragraph 7.6.1.9 [expr.static.cast]/2.

InsertOtherwise, before the text of paragraph7.6.1.9 [expr.static.cast]/2(which will become 7.6.1.9 [expr.static.cast]/3after the above insertion), so that itreads:

Otherwise, an expressionecan be explicitly converted to a typeTusing astatic_castof the formstatic_cast<T>(e)if the declaration"T t(e);"is well-formed, for some invented temporary variablet(9.5 [dcl.init]).The effect of such an explicit conversion is the same as performing thedeclaration and initialization and then using the temporary variableas the result of the conversion.The result is an lvalue ifTis a reference type (9.3.4.3 [dcl.ref]), and an rvalue otherwise.The expressioneis used as an lvalue if and only if the initialization uses it as an lvalue.




[8]ページ先頭

©2009-2026 Movatter.jp