spir Wrote:

> > unittest {
> > string s = "abc";
> > char[] chars = cast(char[])s;
> > chars ~= "de";
> > s = cast(string) chars;
> > writeln(s, ' ', chars); // abcde abcde
> >
> > chars[1] = 'z';
> > writeln(s, ' ', chars); // azcde azcde
> > }
> >
> > s's chars are mutable ;-) So, I guess there is /really/ no reason for 
> > implicite
> > casts between char[] and string no to exist. (I assumed the reason was
> > precisely to avoid such traps).
> 
> After some more thought, I guess it's better to leave things as are. We have 
> a 
> way to cast without copy --which is one issue perfectly solved. The other 
> issue 
> --typing-- is small enough to keep it, since it also serves as warning to the 
> programmer about the above trap.
> What should definitely be done is teaching this idiom in all relevant places 
> of 
> the reference, manuals, tutorials: while this issue is often submitted on D 
> lists, I had never read about it (nore thought about it myself).
> 
> Questions: did you know this idiom? if yes, have you found it yourself or 
> read 
> about it? if the latter, where?

Casting to and from string/char[] is very dangerous, even through assumeUnique. 
AssumeUnique is intended to be used for returning a mutable as immutable from a 
function. Casting is often a no-op for the CPU and as you discovered removes 
any safety provided by the type system.

While modifying immutable data is undefined, if you can guarantee the data 
truly is mutable and the compiler won't be optimizing with the assumption of 
immutability,  it is perfectly safe. It is just in the hands of the programmer 
now.

Reply via email to