alloca() in D

Jonathan M Davis jmdavisProg at gmx.com
Sat Aug 6 00:00:24 PDT 2011


On Friday 05 August 2011 23:35:58 Mehrdad wrote:
> I think D should really have a friendlier interface to stack-based data
> structures than just alloca() (unless it already does and I don't know
> about it).
> 
> Some features which I think would be helpful:
> - An "automatic" array-like structure entirely on the stack that starts
> out with a capacity given by the user), and which switches to the heap
> if it gets too big.

static arrays are always on the stack, but you can't change their size. To do 
what you're asking, you'd need to essentially have a struct which wrapped a 
static array and treated its length as its capacity instead of its length, 
keeping track of the number of elements separately. Then, if you got too many 
elements, it would reallocate it the heap. But it would still be using all of 
that memory on the stack, and if it has much size to it at all, it could get 
expensive to pass it to other functions. It's doable, but I don't see much 
point to it honestly.

> - A function that can just allocate a structure easily on the stack,
> taking care of constructors and whatnot... something like alloca!Foo()
> to allocate Foo on the stack, and alloca!Foo(5) to allocate Foo[] with a
> length of 5 on the stack (NOT Foo[5], obviously...), etc.

structs are on tha stack already. There's no need to do anything special for 
that. And if you want a class on the stack, you use std.typecons.scoped 
(though honestly, I wouldn't generally advise doing that - if you really need 
to do that, there's a good chance that it should have been a struct in the 
first place; passing it to other functions becomes dangerous and you generally 
have to be very careful with classes on the stack).

- Jonathan M Davis


More information about the Digitalmars-d mailing list