in-parameter

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 00:38:54 PST 2010


On Monday 08 November 2010 00:03:55 spir wrote:
> On Mon, 8 Nov 2010 18:13:54 +1000
> 
> "Daniel Murphy" <yebblies at nospamgmail.com> wrote:
> > "spir" <denis.spir at gmail.com> wrote in message
> > news:mailman.157.1289146124.21107.digitalmars-d at puremagic.com...
> > I'd like to know, aside user-side semantics, whether the compiler uses
> > the "in" qualifier for efficiency (pass arrays & structs by ref under
> > the hood?). Well, seems obvious, but there may be some hidden constraint
> > I'm unable to realise.
> > 
> > The spec states: "The in storage class is equivalent to const scope."
> > 
> > So, no, the compiler never implicitly uses ref to pass in parameters.
> > 
> > It could be possible with a rule like "pass by const ref if param.sizeof
> > > x bytes", but I think this would require an abi change.
> 
> Then, if I pass a huge array/string or struct as "in", it is copied, right?
> Is the only way to avoid copy then to pass as ref? I take the opportunity
> to ask about dynamic arrays. There is an internally pointed element-array,
> but is the array's interface (the kind of struct holding ptr & length)
> itself implicitely referenced?
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

Dynamic arrays are reference types. A Dynamic array holds the pointer to its 
internal C-style array and the length of that array. It's essentially a struct. 
That struct - being a struct - is copied by value. But since internally, it 
holds a pointer, the new dynamic array struct has a pointer to the same data. 
So, if you alter the elements of that array, it alters the elements of the array 
that was passed in. However, if you alter the arrays size, causing it to have to 
re-allocate memory, then that array is going to be pointing to a different block 
of memory, and it will no longer affect the original array. Dynamic arrays are 
shallow-copied when passed to functions, not deep-copied, so you have to use dup 
or idup if you want to get a full copy which will no longer affect the original 
(or the parameter has to be const or in, so that the function cannot alter the 
array at all).

Now, static arrays _do_ get copied when passed as arguments to functions because 
they're value types, but dynamic arrays are reference types, so they don't.

- Jonathan M Davis


More information about the Digitalmars-d mailing list