When is array-to-array cast legal, and what does actually happen?
Daniel Keep
daniel.keep.lists at gmail.com
Mon Feb 22 17:49:47 PST 2010
> ...
>
> 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. 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.
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.
To answer your question: yes, it's legal. Not what you wanted, but legal.
[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!
More information about the Digitalmars-d-learn
mailing list