"Best" way of passing in a big struct to a function?

Jonathan M Davis jmdavisProg at gmx.com
Tue Oct 9 21:52:25 PDT 2012


On Wednesday, October 10, 2012 06:39:51 Val Markovic wrote:
> On Wednesday, 10 October 2012 at 04:55:48 UTC, Val Markovic wrote:
> > Oh, and a related question: what is the best way to pass in an
> > associative array like CustomStruct[string]? I can't say I'm
> > too clear on how AA's are managed/implemented. Do they have
> > value semantics or reference semantics? What about lists?
> 
> Ok, feel free to disregard this question; I just checked TDPL
> (should have done that first) and it clearly says that AA's
> follow reference semantics. Dynamic arrays passed to functions
> actually pass in a light-weight object referring to the same
> underlying data (I'm guessing that a dynamic array is internally
> "nothing more" than a struct holding a pointer and a length,
> right?).

A dynamic array is effectively

DynamicArray(T)
{
    T* ptr;
    size_t length;
}

So, they're sort of reference types, sort of not. Passing a dynamic array by 
value will slice it, allowing the elements to still be mutated (because they 
point to the same memory) if they're mutable, but if you alter the array 
itself, it won't alter the original, and if you alter it enough, it could end 
up copying the array so that it's not a slice anymore (e.g. appending could 
require reallocating the array to make room for the new elements, thereby 
changing the ptr value from what it was originally).

You should read this article: http://dlang.org/d-array-article.html

Associative arrays on the other hand are entirely reference types. The one 
thing that you need to watch out for is that if you pass one to a function, 
and it's null, then when you add elements to it, it will create a new AA for 
the local variable in that function but not affect the one passed in (which is 
still null). But if it's non-null when it's passed in, then anything done to 
it in the function that it was passed to will affect the original (since 
they're one and the same).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list