Allocators stack

Rikki Cattermole via Digitalmars-d digitalmars-d at puremagic.com
Mon Dec 22 16:07:30 PST 2014


On 23/12/2014 5:51 a.m., Allocator stack wrote:
> How about allocators stack? Allocator e.g. one of these
> https://github.com/andralex/phobos/blob/allocator/std/allocator.d
> -------------
> allocatorStack.push(new GCAllocator);
> //Some code that use memory allocation
> auto a = ['x', 'y'];
> a ~= ['a', 'b']; // use allocatorStack.top.realloc(...);
> allocatorStack.pop();
> -------------
> Allocators must be equipped with dynamic polymorphism. For those
> cases when it is too expensive attribute
> @allocator(yourAllocator) applied to declaration set allocator
> statically.
>
> -------------
> @allocator(Mallocator.instance)
> void f()
> {
> // Implicitly use global(tls?) allocator Mallocator when allocate an
> object or resize an array or etc.
> }
>
> @allocator("StackAllocator")
> void f()
> {
> // Implicitly use allocatorStack.top() allocator when allocate an
> object or resize an array or etc.
> }
> -------------
>
> There is some issues to solve. E.g. how to eliminate mix memory from
> different allocators.

I've also come up with a way to do this.
Using the with statement and a couple extra functionality.

with(new MyAllocator()) { // myAllocator.opWithIn();
	Foo foo = new Foo(1); // myAllocator.alloc!Foo(1);
} // myAllocator.opWithOut();

class MyAllocator : Allocator {
	private {
		Allocator old;
	}

	void opWithIn() {
		old = RuntimeThread.allocator;
		RuntimeThread.allocator = this;
	}

	void opWithout() {
		RuntimeThread.allocator = old;
	}
}

I'm sure you get the gist.


More information about the Digitalmars-d mailing list