How do you deal with scoped allocations?

Namespace rswhite4 at googlemail.com
Sat Dec 7 15:26:03 PST 2013


On Saturday, 7 December 2013 at 23:21:05 UTC, Adam D. Ruppe wrote:
> On Saturday, 7 December 2013 at 22:32:59 UTC, Namespace wrote:
>> Since D doesn't offer VLA's and alloca is broken (besides the 
>> ugly syntax),
>> I use a scoped wrapper (since scope doesn't do the job):
>
> I like to use a helper template that defines a static array 
> with a typical size. Then, if the runtime requirement is less 
> than that, it can simply slice into the static array, and if 
> not, then do the alloc/free pair.

You mean something like that?

----
struct Helper(T, uint StackSize = 128) {
	static T[StackSize] buffer = void;

	static T[] opCall(size_t n) {
		if (n <= StackSize)
			return buffer[0 .. n];

		return new T[n];
	}
}

void main() {
	int[] arr = Helper!int(512);
}
----


More information about the Digitalmars-d mailing list