On 04/07/2011 09:01 AM, Simen kjaeraas wrote:
> On Thu, 07 Apr 2011 02:13:16 +0200, bearophile
> <bearophileh...@lycos.com> wrote:
>
>> Given an array of strings std.string.join() returns a single string:
>>
>> import std.string;
>> void main() {
>> string[] a1 = ["hello", "red"];
>> string j1 = join(a1, " "); // OK
>> }
>>
>>
>> But in a program I need an array of mutable arrays of chars. If I join
>> the arrays I get a mutable array of chars. But I need a string:
>>
>> import std.string;
>> void main() {
>> char[][] a2 = ["hello".dup, "red".dup];
>> string j2 = join(a2, " "); // error
>> }
>>
>> Error: cannot implicitly convert expression (join(a," ")) of type
>> char[] to string
>>
>> .idup avoids the error:
>>
>> string j3 = join(a2, " ").idup; // OK
>>
>> Given the low efficiency of the D GC it's better to reduce memory
>> allocations as much as possible.
>> Here join() creates a brand new array, so idup performs a useless
>> copy. To avoid this extra copy do I have to write another joinString()
>> function?
>>
>> Bye,
>> bearophile
>
> Isn't this a prime case for std.exception.assumeUnique?

Almost. assumeUnique is too eager and tries to null its reference parameter. Copying from std/exception.d:

immutable(T)[] assumeUnique(T)(ref T[] array) pure nothrow
{
    auto result = cast(immutable(T)[]) array;
    array = null;
    return result;
}

And that fails as join's return type is not an lvalue.

We need a simplyAssumeUnique() that doesn't null the reference parameter :); and it would have no value over casting other than communicating the intent.

Ali

Reply via email to