Proper way of passing array parameters to D functions -
1st question:
are d array function parameters passed reference, or value? also, language implements copy on write arrays? e.g.:
void foo(int[] arr) { // arr local copy or ref external array? arr[0] = 42; // how now? }
2nd question:
suppose have large array passed function foo
read-only parameter , should avoided as possible copying array, since assumed large object. following (or none of them) best declaration function foo
:
void foo(const int[] bigarray) void foo(in int[] bigarray) void foo(const ref int[] bigarray)
technically, dynamic array
int[]
pointer , length. pointer , length copied onto stack, not array contents.arr[0] = 42;
modify original array.
on other side, static arrayint[30]
plain old data type consisting of 30 consecutiveint
s in memory. so, functionvoid foo(int[30] arr)
copy 120 bytes onto stack start. in such case,arr[0] = 42;
modifies local copy of array.according above, each of ways listed avoids copying array contents. so, whether need parameter
const
,in
,const ref
or otherwise depends on trying achieve besides avoiding array copy. example, if passref int [] arr
parameter, not can modify contents, able modify pointer , length (for example, create wholly new array , assignarr
visible outside function).
for further information, please refer corresponding articles on dlang site covering arrays , array slices.
Comments
Post a Comment