ref arguments

Jeremie Pelletier jeremiep at gmail.com
Mon Sep 21 21:58:02 PDT 2009


Saaa wrote:
> Thanks Jeremie Pelletier!
> 
> Good to see I'm not going crazy (<none> /  in)  :)
> just a few small questions:
> 
> What exactly is a storage class?
> Is it this:
> C has a concept of 'Storage classes' which are used to define the scope 
> (visability) and life time of variables and/or functions.

That would be it. The storage class is mostly useful to the compiler to 
determine the semantics of the variable, which will determine where it 
is allocated, its lifetime and its mutability.

> Dynamic arrays are always on the heap, right?

That is correct.

> I never use "new (array)"  nor change references in other ways except 
> changing
> the length.
> I suspect, the old array gets garbage collected if no other references point 
> to it :)
> I also suspect "new (array)"  to never allocate in place even if the length
> is equal or smaller and no other pointers point to the old array, because 
> the
> gc needs to run first to check for this.

I myself use a mix of both new and .length:

new is faster to allocate brand new arrays since there are less internal 
function calls. new, just like malloc in C and as the name implies, 
always allocates new memory.

.length is faster to resize arrays since there are good chances the 
resize can be done in place, for example if it fits in the same memory 
block or if there are enough free contiguous pages following the 
allocation, just like C's realloc.

I also change references all the time, depending on the context. For 
example, when working with file paths, you can send a path to a method 
accepting an immutable(char)[] (or its alias, string) which saves the 
reference somewhere without making a copy, then modify your local 
reference and call another function with the new array. The original 
array won't be garbage collected because it is still referenced, and the 
parameter of type immutable(char)[] instead of const(char)[] specifies 
the data will not change at all; const(char)[] means the callee's scope 
should not modify the data, but other references may be mutable.

It can be a bit confusing at first, especially since immutable and const 
have very similar semantics. But you'll get the hang of it after playing 
with them for some time :)

> In stead of a table I made a nice diagram:
> http://bayimg.com/kAEkNAaCA
> Is it correct? 

That looks good! I would use the terms caller and callee instead of call 
and func however, it would be clearer that way. You might want to add 
headers to the different colums (storage class, scope, reference and 
data respectively), it took me a few seconds to figure the meaning of 
the columns there :) Other than that I believe it reflects the semantics 
used in D1.

Jeremie


More information about the Digitalmars-d-learn mailing list