Passing dynamic arrays

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 10:27:42 PST 2010


On Monday, November 08, 2010 09:40:47 bearophile wrote:
> Jens Mueller:
> > I find this behavior rather strange.
> 
> I don't know if it's strange, but surely it is a little bug-prone corner of
> D. I have had two or three bugs in my code because of that.

I don't know. I find it to be pretty straightforward, though I can understand why 
people would find it to be confusing at first. As long as you don't alter a 
dynamic array's size in any way, then it and any references to it or any part of 
it will continue to point to the same data. If you dup an array, then it's 
guaranteed to point to different data (albeit a copy of that data). If you alter 
the size of an array but don't explicitly dup it, then it _might_ point to the 
same data and it might not (hence the potential confusion).

So, if you want to guarantee that an array continues to point to the same data, 
then just don't alter its size. If you want to guarantee that its copied and 
points to different data, then dup or idup it. If you don't care whether it 
continues to point to the same data or not, then feel free to resize it through 
setting its length or appending to it.

Granted, it's easier to understand what's going on when you understand that a 
dynamic array is essentially

struct array(T)
{
    T* ptr;
    size_t length;
}


but you don't really need to. Truth be told, I don't think that I've _ever_ had 
a bug due to how arrays reallocate. I think that as long as you understand that 
resizing could mean reallocation, it's quite easy to avoid bugs with it. That 
doesn't mean that they'll never happen, but I don't find this particular corner 
of the language to be particularly bug-prone.

- Jonathan M Davis


More information about the Digitalmars-d mailing list