new initializer syntax (was TempAlloc review starts now)

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Jun 5 16:51:41 PDT 2011


> But its usage as expression is not the most nice, so it's probably better to
> disallow this usage:
>
> void foo(int[] a) {}
> main() {
>     foo(new[5] = 5);
> }
>

Might as well change foo to accept a size_t length and initializer,
and let it create an array on the stack or heap, whichever it thinks
is more efficient or safer. Why pass a new heap-allocated array which
you don't have the handle to outside of foo? What's the use-case for
this example?

> There is a very simple syntax, nice and clean:
>
> // doesn't initialize foo1
> auto foo1 = new uint[5] = void;
>
> // initializes the dynamic array to 5, avoiding a double initialization
> auto foo2 = new uint[5] = 10;
>
> // works for nD arrays too
> auto mat1 = new double[][][](n1,n2,n3) = 0.0;
>

I thought about "void new", but I'd rather drop that idea. There's
also that opinion that letting 'new' into the language was a mistake.
I wouldn't mind a template instead of syntax sugar. I'd be fine with:

auto foo = voidNew!(float[][])(4, 10);         // float[10][4], no initializer
auto bar = initNew!(float[][])(4, 10, 5.5);  // float[10][4], all
initialized to 5.5

or make the initializer a CT argument, I think this would be more readable:
auto bar = initNew!(float[][], 5.5)(4, 10);  // float[10][4], all
initialized to 5.5

No need to mess with the compiler, can be implemented with D's
template features. We can have this implemented and unittested in a
day, compared to hacking the compiler and worrying about bugs.


More information about the Digitalmars-d mailing list