new T[size] vs .reserve - alloca

monarch_dodra monarchdodra at gmail.com
Tue Feb 5 08:47:19 PST 2013


On Tuesday, 5 February 2013 at 16:37:41 UTC, Nick Treleaven wrote:
> On 05/02/2013 16:17, Nick Treleaven wrote:
>> On 03/02/2013 13:22, bearophile wrote:
>>> Era Scarecrow:
>>>
>>>> On Sunday, 3 February 2013 at 09:11:59 UTC, Namespace wrote:
>>>>> Sure, but alloca has the same ugly interface as malloc. :/
>>>>
>>>> You mean that you have to specify how many raw bytes you 
>>>> want, then
>>>> cast it to what you need? I never thought alloca or malloc 
>>>> were that
>>>> ugly.
>>>
>>> The interface of alloca() is bug-prone. And it's not handy if 
>>> you want
>>> to create a 2D or nD array on the stack :-) In bugzilla there 
>>> is a
>>> preliminary request for better and less bug-prone VLAs for D.
>>
>> ^ I know you're aware of this, but maybe others might not know 
>> the
>> default-argument alloca wrapping trick:
>
> 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];
}

void main(string[] args)
{
     int*  p   = stack!int();
     int[] arr = stack!(int, 5)();
     *p = 2;
     arr[0] = 5;
     writeln(*p);
     writeln(arr);
}
//----


More information about the Digitalmars-d-learn mailing list