const challenge

Sergey Gromov snake.scaly at gmail.com
Fri Feb 1 11:12:57 PST 2008


Janice Caron Wrote:

> 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.

Of course, you're right.

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

Inline array initialization is also an expression, and unique must survive
to allow the whole array be unique.  Why using in expression makes
data not 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;
>     }

I'm afraid that's not possible if you want strict type safety.  A unique
parameter effectively results in a local variable of type unique.  Or, even
worse, of non-unique type.  In either case, the compiler doesn't have
any chance to check what's happening and enforce type safety.  Which
is a must: implicit conversions must be safe.

So the only way to return a unique result from a function is to dup
or new or inline-construct directly within its return statement.  Other
return values are illegal.

SnakE



More information about the Digitalmars-d mailing list