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)
To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);
There are two possible ways to do so, one by using call by value and other by using call by reference.
An array passed to a function decays into a pointer to its first element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With