When is array-to-array cast legal, and what does actually happen?

Ali Çehreli acehreli at yahoo.com
Mon Feb 22 23:06:36 PST 2010


Daniel Keep wrote:
 >> ...
 >>
 >> I see that neither the constructor nor the postblit is called.
 >> Apparently the bit representation is used. This has the risk of
 >> violating struct invariants.
 >>
 >> Is it legal?
 >>
 >> Thank you,
 >> Ali
 >
 > cast is to value conversions what a tactical nuclear strike is to
 > peaceful negotiations.

Yes, that's the C-style casts...

 >  cast is specifically *designed* to circumvent
 > the type system's protections [1].
 >
 > If you want to do a value conversion, *do a value conversion*.  Allocate
 > a new array and convert each member.  cast doesn't call the constructor
 > or the postblit because it's doing a pointer conversion.

As you point out in the footnote, cast are not always pointer 
conversions. :)

I am wondering whether the compiler could call the constructors for each 
array element in array-to-array conversion.

 > Your code is basically equivalent to this:
 >
 > void main()
 > {
 >     auto tmp = "hello"d;
 >     auto mine = cast(MyChar*)(tmp.ptr)
 >         [0..(tmp.length*typeof(tmp[0]).sizeof)/MyChar.sizeof)];
 > }
 >
 > That is, it's doing an unsafe, unchecked pointer cast, then re-slicing
 > the array.

Especially when there is the method above, it feels more like array 
casting could call the constructors.

 > To answer your question: yes, it's legal.  Not what you wanted, but 
legal.

Actually it will work for me, but I will leave it for later when 
optimizing the code. And there are no invariants in my case; any dchar 
will do.

 > [1] Except for int<->float.  Oh, and objects.  Really, this is one thing
 > I could just about strangle K&R for: conflating value-preserving,
 > non-value-preserving *AND* unsafe conversions all into a single
 > construct.  Walter, gets slapped with a fish for not putting a bullet in
 > cast's head when he had the chance.  Argh!

Ali


More information about the Digitalmars-d-learn mailing list