Guest User

Untitled

a guest
Mar 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. import core.memory : pureMalloc, pureFree;
  2. import object : destroy;
  3.  
  4. // this API supports classes and non-classes with the same functions
  5. auto myAlloc(T, Args...)(auto ref Args ctorArgs) @trusted
  6. {
  7. static if (is(T == class))
  8. {
  9. size_t bytes = __traits(classInstanceSize, T); // this is because classes are reference types; therefore T.sizeof == sizeof the class reference (pointer)
  10. alias ReturnType = T; // classes are references, so you don't handle them by pointer
  11. }
  12. else
  13. {
  14. size_t bytes = T.sizeof;
  15. alias ReturnType = T*;
  16. }
  17.  
  18. ReturnType obj = cast(ReturnType)pureMalloc(bytes); // allocate memory for object
  19. return emplace!T(obj, ctorArgs); // construct object
  20. }
  21.  
  22. void myFree(T)(T object) if (is(T == class)) // again, since classes are references, they aren't passed by pointer
  23. {
  24. destroy(object);
  25. pureFree(cast(void*)object);
  26. }
  27. void myFree(T)(T* object) if (!is(T == class))
  28. {
  29. destroy(*object);
  30. pureFree(cast(void*)object);
  31. }
Add Comment
Please, Sign In to add comment