[Issue 6421] Require initialization of static arrays with array literals not to allocate
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Mon May 5 04:56:43 PDT 2014
https://issues.dlang.org/show_bug.cgi?id=6421
--- Comment #16 from bearophile_hugs at eml.cc ---
(In reply to Kenji Hara from comment #7)
> I also think that "static array literal sytax" (eg. DIP34) is not good
> feature.
I still don't know what the best solution is. The $ syntax to infer the number
of items seems good enough.
Regarding the []s syntax, if you have a function template like:
ForeachType!Items sum(Items)(ref Items sequence) {
typeof(return) total = 0;
foreach (x; sequence)
total += x;
return total;
}
If you call it like this it will allocate an array on the heap (it's the
default behavour, I guess):
immutable tot = sum([1, 2, 3]);
If you use a fixed-size literal there is no need for heap allocation and you
can use @nogc:
immutable tot = sum([1, 2, 3]s);
An advantage of the []s syntax is that it always allocates the data on the
stack, so it's very easy for the @nogc to accept such literals in a function.
You can use in a line of code like:
auto t1 = tuple([1, 2]s, "values");
That defines a Tuple!(int[2], string). Currently to do it you must specify the
type:
auto t2 = Tuple!(int[2], string)([1, 2], "values");
This is using the syntax suggested elsewhere in this thread:
auto t3 = tuple(int[2]([1, 2]), "values");
When you have array literals nested in other literals (or nested in other
generic function calls), having the []s syntax is a clear way to tell the
compiler what you want:
auto aa1 = ["key": [1, 2]s];
Instead of:
int[2][string] aa2 = ["key": [1, 2]];
If you have to pass such associative array literal to a function:
foo(["key": [1, 2]s]);
Currently you need to use a not nice and bug-prone cast:
void foo(TK, TV)(TV[TK] aa) {
pragma(msg, TK, " ", TV);
}
void main() {
foo(["key": cast(int[2])[1, 2]]);
}
--
More information about the Digitalmars-d-bugs
mailing list