Behaviour of append (~=)

Chris Miller chris at dprogramming.com
Tue May 30 06:56:01 PDT 2006


On Tue, 30 May 2006 07:47:22 -0400, Derek Parnell <derek at psych.ward> wrote:

> On Tue, 30 May 2006 21:37:02 +1000, Lionello Lunesu  
> <lio at lunesu.remove.com> wrote:
>
>> Why does the appending to a 'null' array cause the contents to be  
>> copied?
>>
>> int[] ar1; // some array, not constant
>>
>> int[] ar2 = null;
>> ar2 ~= ar1;
>> // ar2 !is ar1
>>
>> But it could be like this:
>> if (ar2)
>>    ar2 ~= ar1;
>> else
>>    ar2 = ar1;
>>
>> Wouldn't it be a good optimization for ~= to check for null first, to  
>> prevent the copy?
>
> Not so sure, because for consistency sake its good to know that 'append'  
> will always do a copy. Then we can rely on this to happen.
>

Exactly; many, many times I rely on this behavior. If it is changed, a lot  
of memory will be overwritten unintentionally and broken code will result.  
Consider the following code if ~= is changed:
    foo ~= bar[0 .. n];
    foo ~= baz; // likely corruption after bar[n].
It's kind of like saying, why require ~ to copy when you can just use and  
overwrite the memory after the first operand. Too many people rely on ~  
copying.



More information about the Digitalmars-d-learn mailing list