Segfault when casting array of Interface types

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 15 22:53:52 PDT 2014


On 09/15/2014 07:21 PM, rcor wrote:
> I'm back for another round of "is this a bug, or am I doing something
> stupid?".
>
> C and D implement interface I, and I have an array of each. I'd like to
> combine these into one I[], but eventually I'd like to cast an element
> back to its original type.
>
> interface I {}
> class C : I {}
> class D : I {}
>
> void main() {
>    C[] c = [new C, new C];
>    D[] d = [new D, new D];
>    auto i = cast(I[]) c ~ cast(I[]) d;
>    assert(cast(C) i[0]); // segfault
> }
>
> casting each array to I[] is fine, but casting an element back to C
> segfaults (even if it weren't a C, it should just return null, right?)

I don't have an answer and I am not even sure whether this is a bug. 
However, std.conv.to works with the example:

import std.conv;

interface I {}
class C : I {}
class D : I {}

void main() {
   C[] c = [new C, new C];
   D[] d = [new D, new D];

   auto i = c.to!(I[]) ~ d.to!(I[]);    // <-- here
   assert(cast(C)(i[0]));
}

Ali



More information about the Digitalmars-d-learn mailing list