On Thu, 18 Feb 2010 20:47:16 -0500, Denis Koroskin <[email protected]>
wrote:
On Fri, 19 Feb 2010 00:46:05 +0300, Steven Schveighoffer
<[email protected]> wrote:
That would be bad, T[] is implicitly casted from T[N]. Consider that
you could easily escape stack data using this. In other words, the
type system would allow the assignment without the dup.
-Steve
I don't think so. First of all, it is consistent with current behavior:
int[] foo()
{
int[3] staticArray = [0, 1, 2];
int[] dynamicArray = staticArray;
return dynamicArray;
}
Here is the case I'd say looks bad to me:
int[] foo()
{
int[] dynamicArray = [0, 1, 2];
return dynamicArray;
}
If [0, 1, 2] is a static array, then it escapes its scope and corruption
ensues. The implicit static array is the problem, not the assigning of a
dynamic array from a static array. The literal doesn't look like it's a
static array.
Second, it's very useful to prevent unnecessary heap allocations.
This is already available by using a static array explicitly. The
question is, what should be the default? I think making it immutable and
non-static is the right choice because it can always escape scope, and
does not require an allocation. From there you can do either a static
array if you know it won't escape scope, or a dynamic array (via dup) if
you need to modify it and it will escape scope.
I would prefer static arrays not to cast to dynamic ones implicitly, but
using opSlice syntax instead:
int[] arr = [0, 1, 2]; // error
int[] arr = [0, 1, 2][]; // fine, use on your own risk
This is just an annoyance error. What will happen is people will
constantly just use the brackets to shut up the compiler without thinking
about what it really means.
-Steve