xxxxxxxxxx
import std.experimental.allocator : allocatorObject, make, dispose, theAllocator;
import std.experimental.allocator.mallocator : Mallocator;
auto alloc(alias Allocator, T, A...)(auto ref A args)
{
if (__ctfe)
{
return new T(args);
}
else
{
return Allocator.make!T(args);
}
}
auto del(alias A, T)(auto ref T* p)
{
if (__ctfe)
{
// nop
}
else
{
A.dispose(p);
}
}
auto foo()
{
// use default allocator
auto x = alloc!(theAllocator, int);
scope(exit) del!theAllocator(x);
*x = 10;
return *x;
}
auto bar()
{
// use specified allocator
auto x = alloc!(Mallocator.instance, int);
scope(exit) del!(Mallocator.instance)(x);
*x = 10;
return *x;
}
void main()
{
enum f = foo();
static assert(f == 10);
enum b = bar();
static assert(b == 10);
// test that alloc and del can be used at runtime
auto allocator = allocatorObject(Mallocator.instance);
auto x = alloc!(allocator, int);
scope(exit) del!allocator(x);
*x = 10;
assert(*x == 10);
}