new T[size] vs .reserve - alloca

Nick Treleaven ntrel-public at yahoo.co.uk
Tue Feb 5 12:47:41 PST 2013


On 05/02/2013 16:47, monarch_dodra wrote:
> On Tuesday, 5 February 2013 at 16:37:41 UTC, Nick Treleaven wrote:
>> I've just realized this doesn't work for variable-length allocation:
>>
>> T[] stack(T)(size_t N, void* m = alloca(T.sizeof * N))
>>
>> Error: undefined identifier N, did you mean alias T?
>>
>> N is not visible in the caller's scope.
>
> It does, just alias it.
>
> //----
> 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];
> }

This works if you know N at compile-time. But there doesn't seem to be a 
way to wrap alloca to accept a runtime-only value, e.g.:

// allocate as many ints as command-line parameters
int[] arr = stack!int(args.length);


More information about the Digitalmars-d-learn mailing list