How to initialize static arrays with variable data
Steven Schveighoffer
schveiguy at yahoo.com
Fri Feb 19 08:47:09 PST 2010
In another thread, Don (and others including myself) advocate that an
array literal should be an immutable array. This has benefits when you
want to use immutable arrays that have statically determined values. It
means you don't require heap allocations when assigning an immutable
array, just like strings are handled.
The point was brought up by Walter (and previously by others), "what about
initializing non-immutable arrays with runtime-determined data?"
i.e.
int[] x = [a, b, c];
The answer is simply, use a library function to allocate the array on the
heap.
i.e.
int[] x = toArray(a, b, c);
This works great, but there is still one missing piece that was pointed
out by Denis Koroshin and grauzone. What about static arrays that you
*don't* want to initialize on the heap?
i.e.
int[3] x = [a, b, c];
Currently, the act of making an array literal allocates on the heap. If
array literals become immutable, then you can't do [a, b, c] because it is
determined at runtime. So how can this be made to work? Should it be a
library function?
i.e.
int[3] x = toStatic(a, b, c);
Or should the compiler do something magic, such as type array literals
with runtime values in them as a static array? It would be nice to allow
this:
int[3] x = [a, b, c];
but then to be safe (so you cannot easily construct an escaping array) you
cannot allow this:
int[] x = [a, b, c];
Any other ideas? I think this problem really needs a solution if we are
going to address array literals.
-Steve
More information about the Digitalmars-d
mailing list