"Best" way of passing in a big struct to a function?
Jonathan M Davis
jmdavisProg at gmx.com
Wed Oct 10 00:04:36 PDT 2012
On Wednesday, October 10, 2012 08:59:54 thedeemon 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?
>
> Good question, I'd like to get some clarification on it too.
> Because it doesn't behave like, for example, class which surely
> has reference semantics.
>
> When I've got a class
>
> class C {
> int m;
> }
>
> and pass an object of this class to a function,
>
> void mutate_C(C c)
> {
> c.m = 5;
> }
>
> it follows reference semantics and its contents gets changed.
>
> However if I pass an assoc. array to a function which changes its
> contents
>
> void mutate_AA(string[int] aa)
> {
> foreach(i; 0..10)
> aa[i*10] = "hi";
> }
>
> Then this code
>
> string[int] aa;
> mutate_AA(aa);
> writeln(aa);
>
> outputs "[]" - changes are not applied.
> It's only after I change parameter to "ref string[int] aa" its
> value get changed successfully.
The exact same thing would happen with a class. The problem is that the aa
that you pass in is null, so if you assign anything to it within the function
or otherwise mutate it, it doesn't affect the original. Making it ref fixes the
problem, because then anything which affects the AA variable inside of the
called function is operating on a reference to the original AA variable rather
than just operating on what the original AA variable pointed to. Making sure
that the aa has been properly initialized before passing it to a function
(which would mean giving it at least one value) would make the ref completely
unnecessary.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list