www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Upcasting slice of class elements

reply =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
Why isn't

     class X {}
     class Y : X {}
     X[] xs = cast(X[])(Y[].init);

compilable in safe D?

What's unsafe about such a cast?
Jan 05 2018
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 5 January 2018 at 22:16:04 UTC, Nordlöw wrote:
 Why isn't

     class X {}
     class Y : X {}
     X[] xs = cast(X[])(Y[].init);

 compilable in safe D?

 What's unsafe about such a cast?
class X {} class Y : X {} class Z : X {} Y[] ys = Y[].init; X[] xs = cast(X[])(ys); xs[0] = new Z; What happens to ys[0] there?
Jan 05 2018
prev sibling next sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
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
Jan 05 2018
prev sibling parent reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Fri, Jan 05, 2018 at 10:16:04PM +0000, Nordlöw via Digitalmars-d-learn wrote:
 Why isn't
 
     class X {}
     class Y : X {}
     X[] xs = cast(X[])(Y[].init);
 
 compilable in safe D?
 
 What's unsafe about such a cast?
Your original code snippet seems redundant. If you wanted an empty array of X's, there's no need to cast it from an array of Y's. Perhaps you had something like this in mind instead?: X[] xs = [ cast(X) new Y(...), new Y(...), ... ]; The cast is only needed for the first element; common type inference takes care of the rest of the array. T -- Give a man a fish, and he eats once. Teach a man to fish, and he will sit forever.
Jan 05 2018
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 1/5/18 6:04 PM, H. S. Teoh wrote:
 On Fri, Jan 05, 2018 at 10:16:04PM +0000, Nordlöw via Digitalmars-d-learn
wrote:
 Why isn't

      class X {}
      class Y : X {}
      X[] xs = cast(X[])(Y[].init);

 compilable in safe D?

 What's unsafe about such a cast?
Your original code snippet seems redundant. If you wanted an empty array of X's, there's no need to cast it from an array of Y's. Perhaps you had something like this in mind instead?: X[] xs = [ cast(X) new Y(...), new Y(...), ... ]; The cast is only needed for the first element; common type inference takes care of the rest of the array.
Hm... I tried just this and it works: X[] xs = [new Y]; I think for non-class types it may need more casting. -Steve
Jan 05 2018