ref arguments

Saaa empty at needmail.com
Mon Sep 21 17:29:31 PDT 2009


Jeremie Pelletier wrote:

> You cannot have static array be ref or out. You must use int[] arr instead 
> and let the caller specify the length.
>
> Array in D are already references to their data, it's a 8bytes (or 16bytes 
> on x64) value containing a pointer and a length.

Ok, this I got correct :)

>So the following prototype: void func(<none>/in/ref/out int[] arr);
>
> would have the following semantics:
>
> "<none>" copies the array reference, the referenced data is mutable. 
> Modifying the local reference does not change the caller's reference.

Modifying the local referenced data does not change the caller's referenced 
data.
So only if the referenced data is mutated, a copy will be made?
Test seems to back this up.

> "in" copies the array reference, the local reference AND the referenced 
> data are immutable in the method's scope.

What, there is a difference between <none> and "in" ??
Where can I about read this?
In the example "int foo(int x, ..." on the functions page x is "in".
Are we maybe talking about a different D? D1
I really really wish to understand this stuff.
<info> I know about how in c a function stack is created.

> "ref" passes a reference to the caller's array reference, the referenced 
> data is mutable. Modifying the local reference also changes the caller's 
> reference.

Same as <none> except that it doesn't create a copy on mutate?

> "out" passes a reference to the caller's array reference. The referenced 
> array reference is zeroed and can be modified by the local reference.

Compared to returning a locally(to the function) created array, here
no allocation might be needed if the passed array is big enough.

>
> If you want a mutable reference to an immutable view on the referenced 
> data, use const(int)[], which can also be ref or out.

out const(int)[] will create a array of zero's which you cannot change?

Why isn't there a nice table about this?
columns: local reference/data with/without mutation, caller reference/data 
with/without mutation
rowns: <none>, in, out, ref
cells: array.ptr/length/data
Or, where should I put it after creating it.

> void  func(in/out/ref int i)
>
> "<none>" would be a mutable copy.
> "in" would be immutable copy.
I can't get over the idea that in and none aren't the same
Really, D1? :D
In my test program I can change local i using "in"

> "out" is a reference to the caller's int initialized to 0.

> "ref" is a reference to the caller's int.

> "in" and "const" are only really useful with types which are already 
> references, such as pointers, arrays and objects.

Hope I got it right.. 




More information about the Digitalmars-d-learn mailing list