new T[size] vs .reserve - alloca
Nick Treleaven
ntrel-public at yahoo.co.uk
Tue Feb 5 08:17:26 PST 2013
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:
import std.stdio;
import core.stdc.stdlib:alloca;
T *stack(T)(void* m = alloca(T.sizeof))
{
return cast(T*)m;
}
void main(string[] args)
{
auto i = stack!int();
*i = 5;
writeln(*i);
writeln(i);
int j;
writeln(&j);
}
More advanced behaviour e.g. switching to heap allocation for large
sizes of T may be possible.
More information about the Digitalmars-d-learn
mailing list