Why string alias is invariant ?

Janice Caron caron800 at googlemail.com
Thu Jan 31 00:25:05 PST 2008


On Jan 30, 2008 11:03 PM, Sergey Gromov <snake.scaly at gmail.com> wrote:
> You can't assign a dynamically created data to a variable of type string.

Correct, and this is a good default. There are, of course, times when
the default is not what you want. Others have suggested "idup" as the
solution, but that means an extra copying pass. Forturnately, however,
there is a solution which does /exactly/ what you want, with no
superflous copying. It is this:

    import std.contracts;

    char[] buffer = whatever;
    string s = assumeUnique(buffer);


> You can't pass a dynamically created data into a function receiving string!

Again, correct. This is also a good thing. It allows copy-on-write to
work correctly. For example, consider a function which lowercases a
string. Since string is invariant, that means that when lowercasing
something that is /already/ lowercase, the function is free to return
the original string. If string were merely const (as opposed to
invariant), it would have to make a copy every time.

Again, assumeUnique is your friend. (But don't lie to the compiler or
things will go badly wrong!)


> P.S.  Many thought mus be put into choosing a return type for a library function.  Because if it returns a unique copy of data it must be char[] so that i'm free to modify it.

Well, consider again the example of lowercasing a string to see why
that is not so. If I return the original string (not a copy of it),
then you are /not/ free to modify it, because there might be other
pointers to that data. So you must first copy it (using dup) and then
you can modify the copy. This means that the copy need be done /only
when it is required/, instead of every single time you call the
function - so yes, it is an improvement in efficiency.



More information about the Digitalmars-d mailing list