Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import core.memory : pureMalloc, pureFree;
- import object : destroy;
- // this API supports classes and non-classes with the same functions
- auto myAlloc(T, Args...)(auto ref Args ctorArgs) @trusted
- {
- static if (is(T == class))
- {
- size_t bytes = __traits(classInstanceSize, T); // this is because classes are reference types; therefore T.sizeof == sizeof the class reference (pointer)
- alias ReturnType = T; // classes are references, so you don't handle them by pointer
- }
- else
- {
- size_t bytes = T.sizeof;
- alias ReturnType = T*;
- }
- ReturnType obj = cast(ReturnType)pureMalloc(bytes); // allocate memory for object
- return emplace!T(obj, ctorArgs); // construct object
- }
- void myFree(T)(T object) if (is(T == class)) // again, since classes are references, they aren't passed by pointer
- {
- destroy(object);
- pureFree(cast(void*)object);
- }
- void myFree(T)(T* object) if (!is(T == class))
- {
- destroy(*object);
- pureFree(cast(void*)object);
- }
Add Comment
Please, Sign In to add comment