Inability to dup/~ for const arrays of class objects

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 3 21:25:26 PDT 2013


On Mon, 03 Jun 2013 23:38:12 -0400, Peter Williams  
<pwil3058 at bigpond.net.au> wrote:

> On 04/06/13 11:56, Steven Schveighoffer wrote:
>> On Mon, 03 Jun 2013 20:06:14 -0400, Peter Williams

>>> auto tmp = a[i + 1..$];
>>> a.length = i;
>>> a ~= tmp;
>>>
>>> would be more efficient?
>>
>> No, because that will also reallocate,
>
> Wouldn't the a.length = i prevent that?

No.  The runtime specifically will reallocate on this case.

It does not know that tmp is never going to be used again, nor does it  
know that there aren't any other references to the data past i.  It MUST  
reallocate to avoid stomping (in fact, prior to my changes it DID  
overwrite).

Case in point, if it didn't reallocate, the above would be copying tmp  
over itself, offset by one!

The runtime expects that when it is appending data, it is doing so into  
space that is currently unused.  You can use assumeSafeAppend to tell it  
"the data after this is unused", but then it better be unused :)  In your  
case, you are using it (via tmp), so that doesn't work.

>> For some reason, D doesn't support overlapping moves,
>
> Probably because there's some instances where it would be a disaster and  
> explaining all the cases where you can and can't becomes too difficult  
> so it's just easier to say no to all cases.

No, memmove is valid C code and supports overlapping writes.  It's not as  
optimized as memcpy, which does not.

But I don't know exactly what the difference is.  A simple check at the  
beginning can determine which mode to use, memmove should devolve to  
memcpy if there is no overlap.  And in some cases, the compiler  
specifically knows whether there is overlap at compile time.

-Steve


More information about the Digitalmars-d mailing list