Implicit conversion of unique objects to mutable and immutable

Ali Çehreli acehreli at yahoo.com
Tue Jun 21 18:25:01 PDT 2011


On Wed, 22 Jun 2011 00:31:19 +0000, Jonathan M Davis wrote:

> As I said, in Phobos, when a new string must be allocated, the type
> returned is generally string (so it's immutable), whereas if the result
> of the function is likely to be slice of the string passed in, then the
> function is templated to return the same type of string as was passed to
> it.

I am talking about a freshly manufactured string. There is no parameter 
that is passed to the function in my example. If there is, the function 
probably takes them by const char[] so that any type of string can be 
used.

Let's assume that this function just uses a and b to produce the result:

char[] foo(const char[] a, const char[] b)
{
    // ...
    return fresh_mutable_result;
}

Taking 'const char[]' is the most useful because mutable and immutable 
can be passed. The function is not insisting on immutability because 
there is no reason for it to require that.

The return type is similar: The function should not insist on 
immutability of the result if the result is not really immutable.

> There's no extraneous copying going on in order to return string.

Agreed: No copy when returning. But there will be a copy when the caller 
wants to further mutate the result:

import std.exception;

string foo()
{
    char[] result;
    return assumeUnique(result);    // <-- no copy here
}

void main()
{
    char[] s = foo().dup;    // <-- COPY through .dup here
}

The caller cannot safely cast the string to char[] because there is no 
guarantee other than documentation (which may be outdated as the function 
is modified in the future).

> The _only_ case where it's arguably forced on the caller is in the case
> where a copy _must_ be made, in which case the function returns string
> rather than char[].

No. In the above code there is no need for a copy because the returned 
string is actually mutable. But the caller must make a copy because of 
not being certain whether the returned string is really mutable or 
immutable.

> - Jonathan M Davis

Ali


More information about the Digitalmars-d-learn mailing list