1st Question:
Are D array function parameters always passed by reference, or by value? Also, does the language implements Copy on Write for arrays? E.g.:
void foo(int[] arr)
{
// is arr a local copy or a ref to an external array?
arr[0] = 42; // How about now?
}
2nd Question:
Suppose I have a large array that will be passed to function foo
as a read-only parameter and it should be avoided as much as possible copying the array, since it is assumed to be a very large object. Which from the following (or none of them) would be the best declaration for function foo
:
void foo(const int[] bigArray)
void foo(in int[] bigArray)
void foo(const ref int[] bigArray)
Technically, a dynamic array like int[]
is just a pointer and a length. Only the pointer and length get copied onto the stack, not the array contents. An arr[0] = 42;
does modify the original array.
On the other side, a static array like int[30]
is a plain old data type consisting of 30 consecutive int
s in memory. So, a function like void foo(int[30] arr)
would copy 120 bytes onto the stack for a start. In such a case, arr[0] = 42;
modifies the local copy of the array.
According to the above, each of the ways you listed avoids copying the array contents. So, whether you need the parameter to be const
, in
, const ref
or otherwise depends on what you are trying to achieve besides avoiding array copy. For example, if you pass a ref int [] arr
parameter, not only you can modify its contents, but also you will be able to modify the pointer and length (for example, create a wholly new array and assign it to arr
so that it is visible from outside the function).
For further information, please refer to the corresponding articles on the DLang site covering arrays and array slices.