[Issue 6421] Require initialization of static arrays with array literals not to allocate

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sun May 4 03:34:17 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=6421

--- Comment #6 from Kenji Hara <k.hara.pg at gmail.com> ---
(In reply to bearophile_hugs from comment #0)
> From a comment by Peter Alexander:
> 
> > int[3] a = [1, 2, 3]; // in D, this allocates then copies
> > int a[3] = {1, 2, 3}; // in C++, this doesn't allocate

This is already fixed issue 2356.

And in git-head, more than cases will be fixed.

int[3] a = [1, 2, 3];  // not allocated
a = [1, 2, 3];         // not allocated in git-head

> Some comments received:
[snip]

> How do you specify this in the D language definition? What are the corner
> cases?

I think this is the most better definition about the issue.

"If an array literal could be deduced as static array, and it won't escape from
its context, it would be allocated on stack."

For example:

int[3] a = [1, 2, 3];
-> OK: The array initializer could be typed as int[3] from the variable type

a = [1, 2, 3];
-> OK: The assignment rhs should have same type with the assigned lvalue.
Therefore the array literal could be typed as int[3].

void foo(int[3] a);
foo([1, 2, 3]);
-> OK: The required argument type is int[3].

int[] a = [1, 2, 3];
-> Cannot be allocated on stack, because the memory can escape via the
indirection 'a'.

--


More information about the Digitalmars-d-bugs mailing list