ref parameter qualifier and static arrays
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Sep 9 13:35:52 PDT 2015
On Wednesday 09 September 2015 22:18, Paul wrote:
>
> Is it possible to call a function like this...
>
> void foo(ref int[] anArray)
>
> ...with slices of static arrays? I thought I might be able to use
> [0..$-1] but to no avail - I get an error like this (which is
> confusing!):
>
> (ref int[] anArray) is not callable using argument types (int[])
Slice expressions are not lvalues (can't take their addresses), so you can't
pass them in ref parameters. You can store the slice in a variable and pass
that:
----
void f(ref int[] x) {}
int[3] a;
version(none) f(a[]); /* Nope, a[] is not an lvalue. */
int[] s = a[];
f(s); /* Ok, s is an lvalue. */
----
But if you want to pass slice expressions, then you probably don't need that
ref.
When you pass a slice (without ref), what's actually passed is a pointer and
length. The contents are not copied. That means, when you alter an array
element, the change will be done the original, even without ref:
----
void f(int[] x) {x[0] = 1;}
int[3] a = [0, 0, 0];
f(a[]);
assert(a[0] == 1); /* passes */
----
ref would allow you to resize the original dynamic array:
----
void f(ref int[] x) {x ~= 4;}
int[] a = [1, 2, 3];
f(a);
assert(a.length == 4); /* passes */
----
But there's no point in doing that to temporaries like slice expressions.
More information about the Digitalmars-d-learn
mailing list