Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Last active December 17, 2015 07:39
Show Gist options
  • Save JakobOvrum/5574550 to your computer and use it in GitHub Desktop.
Save JakobOvrum/5574550 to your computer and use it in GitHub Desktop.
malloc/free wrappers for classes
import core.exception : onOutOfMemoryError;
import core.stdc.stdlib : malloc, free;
import std.conv : emplace;
T alloc(T, Args...)(auto ref Args args) if(is(T == class))
{
enum size = __traits(classInstanceSize, T);
if(auto p = malloc(size))
{
scope(failure) free(p);
return emplace!T(p[0 .. size], args);
}
else
onOutOfMemoryError();
}
void dealloc(T)(ref T obj) if(is(T == class))
{
scope(exit)
{
free(cast(void*)obj);
obj = null;
}
destroy(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment