Should conversion of mutable return value to immutable allowed?

Simon Buerger krox at gmx.net
Thu Feb 24 11:20:01 PST 2011


On 24.02.2011 19:08, Ali Çehreli wrote:
> Implicit conversions to immutable in the following two functions feel
> harmless. Has this been discussed before?
>
> string foo()
> {
> char[] s;
> return s; // Error: cannot implicitly convert expression
> // (s) of type char[] to string
> }
>
> string bar()
> {
> char[] s;
> return s ~ s; // Error: cannot implicitly convert expression
> // (s ~ s) of type char[] to string
> }
>
> Is there a reason why that's not possible? I am sure there must be
> other cases that at least I would find harmless. :)
>
> Ali

Currently, the correct way to do it is to use the phobos function 
assumeUnique, like:

string bar()
{
char[] s;
return assumeUnique(s);
}

Note that this does only little more than casting to immutable, so you 
have to ensure there is no mutable reference left behind.

Anyway, it might be nice if the compiler could detect some trivial 
cases and insert the cast appropriately. But on the other hand, the 
compiler will never to be able to auto-detect all cases, and so its 
cleaner to use assumeUnique explicitly.

- Krox


More information about the Digitalmars-d mailing list