new T[size] vs .reserve - alloca

monarch_dodra monarchdodra at gmail.com
Tue Feb 5 14:15:19 PST 2013


On Tuesday, 5 February 2013 at 21:14:32 UTC, Nick Treleaven wrote:
> On 05/02/2013 21:13, Nick Treleaven wrote:
>> I've just tried it with dmd 2.059 (haven't upgraded yet)
>
> sorry, 2.060

Right, it's "alias" being finicky, because "args.length" isn't an 
actual variable (it's a property). The problem is not so much 
that it can't be "read" at compile time, that the compiler 
doesn't know what to alias to.

I'll file a bug report to try and see if we can't get a better 
message.

Use a named variable, or use a manifest constant:

//----
import std.stdio;
import core.stdc.stdlib:alloca;

T* stack(T)(void* m = alloca(T.sizeof))
{
     return cast(T*)m;
}
T[] stack(T, alias N)(void* m = alloca(T.sizeof * N))
{
     return (cast(T*)m)[0 .. N];
}

void main(string[] args)
{
     auto n = args.length;
     int[] arr = stack!(int, n)();
}
//----


More information about the Digitalmars-d-learn mailing list