Unshaped interpretation of static casting
I came across the following code (section 5.4 / 4 N3797):
struct A { };
struct I1 : A { };
struct I2 : A { };
struct D : I1, I2 { };
A* foo( D* p ) {
return (A*)( p ); // ill-formed static_cast interpretation
}
I tried to understand this example, but cannot. I haven't used it static_cast
at all in this example. How does this compare with static_cast
. In general, can you explain the error.
source to share
"C style styles" are called "explicit type conversion" and are discussed in section 5 if the C.11 standard. In point 4:
Conversions done with - a
const_cast
(5.2.11),
- astatic_cast
(5.2.9),
- astatic_cast
followed by aconst_cast
,
- areinterpret_cast
(5.2.10), or
- areinterpret_cast
followed byconst_cast
,
can be done using cast explicit type conversion notation.
This basically means it static_cast
can be the result of a cast expression. It then lists some of the conditions under which it is valid static_cast
, and the example you give was an example where it was invalid. Before this example, there was the following text (the very end of & para; 4):
If a transformation can be interpreted in more than one of the ways listed above, the interpretation that appears in the list in the list is used, even if the cast resulting from that interpretation is ill-formed. If a transformation can be interpreted in more than one way as
static_cast
followed by aconst_cast
, the transformation is ill-formed.
The reason the above example is incorrect is I1
because both I2
do not inherit virtual
from A
. Thus, D
one that uses multiple inheritance on I1
and I2
will have two instances in it A
, and therefore an attempt to transfer D *
to A *
has more than one interpretation. The programmer needs to specify which instance A *
to cast to avoid incorrect conversion.
ASCII warning:
+---+ +---+
| A | | A |
+---+ +---+
| |
/_\ /_\
| |
+----+ +----+
| I1 | | I2 |
+----+ +----+
| |
+------.-------+
|
/_\
|
+---+
| D |
+---+
source to share