NotNull pointers

bearophile bearophileHUGS at lycos.com
Tue Aug 30 16:11:20 PDT 2011


Andrei Alexandrescu:

> new Type[n](argument1, argument2, ..., argumentn)

More musings about this.

A generic lazy/eager array comprehension syntax seems better, like (for the eager one):
[Baz(x, x*y) foreach(x; 0 .. 10) if (isGood(x))]


Currently to create an array of structs like this Foo you need to use array append (if you want to keep the x fields mutable):

struct Foo {
    int x;
    const int y;
}
void main() {
    Foo[] foos;
    foos.reserve(10);
    foreach (i; 0 .. 10)
        foos ~= Foo(i, i*10);
}


With an array comp the compiler doesn't need to use an an array append, just array assign (when there is no if condition), that in D is quite faster:

struct Foo {
    int x;
    const int y;
}
void main() {
    auto a = [Foo(i, i*10) foreach(i; 0 .. 10)];
}


I think a good compiler is able to optimize even the following code, removing the array append, but this is less simple to do if the body of foreach becomes more complex, with gotos, etc:

foos.reserve(10);
foreach (i; 0 .. 10)
    foos ~= Foo(i, i*10);

Bye,
bearophile


More information about the Digitalmars-d mailing list