Casting char[] ranges to string can lead to unexpected behavior

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 30 20:34:12 PDT 2014


On Fri, Oct 31, 2014 at 02:03:58AM +0000, Domingo via Digitalmars-d-learn wrote:
> I spent two days to find a nasty aleatory problem due to a string been
> assigned a range from a char[] array.
> 
> This issue on vibe.d detail it a bit more:
> https://github.com/rejectedsoftware/vibe.d/issues/889
> 
> I'm putting it here to call attention for other developers for this
> problem.
[...]

The problem is not caused by slicing, it's caused by casting a slice of
char[] to string.  Casting char[] to string is a dangerous operation,
because you're operating outside the type system. string is
immutable(char)[], but the original buffer is char[]. Casting it to
string means you're claiming that nobody will modify the char[]
afterwards... but if somebody does modify it later, then you have
violated immutability and broken the type system.

Generally, I recommend using to!string(...) instead of a cast, since
to!string will make a copy of the data if it's not already immutable.
Casts always require extra care because the type system can no longer
help you catch mistakes.


T

-- 
The diminished 7th chord is the most flexible and fear-instilling chord.
Use it often, use it unsparingly, to subdue your listeners into
submission!


More information about the Digitalmars-d-learn mailing list