Why string alias is invariant ?

Janice Caron caron800 at googlemail.com
Thu Jan 31 10:16:08 PST 2008


On 1/31/08, Sergey Gromov <snake.scaly at gmail.com> wrote:
> Maybe a contract should be added for standard library that if a function
> returns a mutable array, it guarantees that this array can be modified
> without side effects and therefore can be safely assumed unique.

Yes, D has a problem here, in that it has no way to express
uniqueness. (That's true of other languages too, of course). If a
string is immutable, then it doesn't /have/ to be unique (but if it
is, it's safe to cast it to invariant), but if a string is mutable
then it /must/ be. That's a problem, because one simply cannot declare

    unique(char)[] array;

(...although it would be interesting to try...) So D just makes it your problem.

One problem area where this sort of thing arises is concatenation. If
you concatenate char arrays, then /regardless/ of the constancy of the
inputs, the result is guaranteed to be unique (because, by
specification, concatenation always makes a copy). If we had a
"unique" type-constructor, one could make the result type unique(T)[].
But we don't, so D makes the (arbitrary) choice of invariant(T)[].
Also, it is currently a syntax error to concatenate a char[] with an
invariant(char)[], even though both will implicitly cast to
const(char)[].

So it's not a perfect system, but it is better than what we had
before, and (I would argue) better than C++. But remember that D2.x is
experimental. We're here to play with it. If we don't like it, things
could change. Our experiences are important here in shaping the
future.



More information about the Digitalmars-d mailing list