Upcasting slice of class elements

Steven Schveighoffer schveiguy at yahoo.com
Fri Jan 5 22:25:01 UTC 2018


On 1/5/18 5:16 PM, Nordlöw wrote:
> Why isn't
> 
>      class X {}
>      class Y : X {}
>      X[] xs = cast(X[])(Y[].init);
> 
> compilable in safe D?

Hm... given that there is no other reference to xs, it should work. But 
obviously you have a different example in mind, as this makes no sense?

This works:

X[] xs = [new Y];

Which really isn't any different.

> What's unsafe about such a cast?
In general:

Y[] ys = ...;
xs = cast(X[])ys;

xs[0] = new X;

ys[0].foo; // oops, ys[0] isn't really a Y any more.

But in your specific case, I think the compiler should see that it's ok.

-Steve


More information about the Digitalmars-d-learn mailing list