How to pass static array to function not by value?
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Nov 22 08:07:31 PST 2014
On Sat, Nov 22, 2014 at 05:57:30PM +0200, ketmar via Digitalmars-d-learn wrote:
> On Sat, 22 Nov 2014 15:45:51 +0000
> Eric via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
> > Maybe this is not so lame because change() can take
> > any length of static array.
>
> void change (int[] arr) {
> arr[1] = 42;
> }
>
> void main () {
> int[$] a = [1, 2, 3];
> change(a);
This is actually really scary that static arrays implicitly decay to a
dynamic array slice. It can cause all sorts of problems with escaping
dangling references to local variables:
Example #1:
int[] bad(int[] arr) {
return arr;
}
int[] equallyBad() {
int[3] x = [1,2,3];
return bad(x); // oops
}
Example #2:
struct S {
int[] data;
this(int[] arr) {
data = arr;
}
}
S makeS() {
int[3] x = [1,2,3];
return S(x); // oops
}
Example #3:
struct S {
int[] data;
this(int[] arr...) { // red flag
data = arr;
}
}
void main() {
auto s = S([1,2,3]); // OK
auto t = S(1,2,3); // NG
}
IMO, at the very least, an explicit slice should be required to turn a
static array into a dynamic array slice. That way, the programmer at
least has to think for 1 second (hopefully more) whether or not he
should be passing a slice to a static array.
T
--
Those who don't understand Unix are condemned to reinvent it, poorly.
More information about the Digitalmars-d-learn
mailing list