Feature: `static cast`

Paul Backus snarwin at gmail.com
Fri Jun 2 17:53:41 UTC 2023


On Thursday, 1 June 2023 at 14:13:27 UTC, Quirin Schroll wrote:
> There’s at least once case where I got bitten by 2. and it cost 
> me days to figure out that, contrary to the spec, casting 
> between `extern(C++)` class references isn’t checked at runtime:
> ```d
> extern(C++) class C { void f() { } }
> extern(C++) class D : C { }
> void main() @safe
> {
>     assert(cast(D)(new C) is null); // fails
> }
> ```
>
> [...] [issue 21690 (Unable to dynamic cast `extern(C++)` 
> classes)](https://issues.dlang.org/show_bug.cgi?id=21690) is 
> solved.

As you say, this is a bug. The cast in the example *should* work 
the same way as `dynamic_cast<D*>(new C())` in C++, but it 
doesn't, because the D compiler doesn't know how to access (or 
generate) the C++ RTTI.

Until the bug is fixed, casts like these should probably be a 
compile-time error ("Error: dynamic casting of C++ classes is not 
implemented"). If you want the current behavior, which is a 
reinterpreting cast, the normal way to write that in D is with a 
pointer cast like `*cast(D*) &c` (which is, appropriately, 
`@system`).

Of course, this would be a fairly disruptive breaking change, so 
it would require a deprecation period, but I think it would be 
worth it to disarm such an obvious footgun.


More information about the Digitalmars-d mailing list