Behaviour of append (~=)
Derek Parnell
derek at psych.ward
Tue May 30 08:44:09 PDT 2006
On Tue, 30 May 2006 23:30:21 +1000, Lionello Lunesu
<lio at lunesu.remove.com> wrote:
> Derek Parnell 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.
>> --Derek Parnell
>> Melbourne, Australia
>
> But, take std.string.replace for example. It only copies when needed.
> Isn't this "exactly what you expect it to do"? I thought this was
> kind-of understood by COW.
But what does the 'replace' function and CoW have to do with this
discussion? All I'm saying that the append operation is always going to
copy the right hand data. If you don't want that behaviour (such as CoW
then only use the append operator when you need to copy the data.)
> Also, I don't think it's safe to rely on the copy to happen. If
> everything follows COW rules, then that's all you need to know, and
> AFAIC ~= copying only iff lhs !is null is a normal COW rule.
But not everything uses or needs CoW. In fact, the append operator is a
useful method to copy something during a CoW function.
--
Derek Parnell
Melbourne, Australia
More information about the Digitalmars-d-learn
mailing list