const challenge

Janice Caron caron800 at googlemail.com
Fri Feb 1 10:51:30 PST 2008


On 2/1/08, Sergey Gromov <snake.scaly at gmail.com> wrote:
> 1. Anything you 'new' is basically unique:
> 2. Any non-unique type within a type casts away uniqueness:
> 3. unique(...) casts to invariant(...), const(...), or just ... implicitly
> with well-defined behavior.
> 4. There is no such thing as unique variable.
>
> Did I miss something ?

Only function returns, I think.

Anything you "new" is unique, and unique things can also be obtained
as function returns (if the function created it with "new" etc).

As soon as you assign it to a variable, or use it in an expression it
stops being unique.

You need a way of expressing that functions can accept unique objects,
and return them. e.g.

    unique(char)[] fillWithSpaces(unique(char)s)
    {
        foreach(ref c;s) c = ' ';
        return s;
    }

We know that s[0] = 'x' has no side effects, because the function has
been promised that there are no other references to s (not even in the
calling code). We similarly promise to the callee that there are no
other references to the return value. Then you get to call it like:

    string s = fillWithSpaces(new char[10]);

so, new creates a unique(char)[]. That gets passed to the function.
The function implicitly casts it to char[], then fills it with spaces.
Then it returns it, and the function return type converts it back to
unique(char)[]. Finally, it's assigned to a variable of type
invariant(char)[].

There was plenty of casting going on there, but all of it was implicit



More information about the Digitalmars-d mailing list