Last active
December 17, 2015 07:39
-
-
Save JakobOvrum/5574550 to your computer and use it in GitHub Desktop.
malloc/free wrappers for classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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