fork download
  1. import std.stdio;
  2. import core.stdc.stdlib;
  3.  
  4. /* ALLOCATION AND DEALLOCATION MECHANISMS */
  5.  
  6. T o_new(T, U...)(U args) if (is(T == class))
  7. {
  8. size_t sz = __traits(classInstanceSize, T);
  9. void[] mem = calloc(sz, byte.sizeof)[0 .. sz];
  10.  
  11. if (mem.length < sz) return null;
  12.  
  13. auto ret = cast(T) mem.ptr;
  14. (cast(byte[]) mem)[0 .. sz] = typeid(T).init[];
  15.  
  16. static if (is(typeof(ret.__ctor(args))))
  17. ret.__ctor(args);
  18. else
  19. {
  20. static assert(
  21. args.length == 0 && !is(typeof(&T.__ctor)),
  22. "No ctor with arguments " ~ U.stringof ~
  23. " present for an object of type " ~ T.stringof
  24. );
  25. }
  26.  
  27. return ret;
  28. }
  29.  
  30. void o_delete(T)(T val) if (is(T == class))
  31. {
  32. static if (is(typeof(val.__dtor())))
  33. val.__dtor();
  34.  
  35. free(cast(void*) val);
  36. }
  37.  
  38.  
  39. class Foo
  40. {
  41. this() { writeln("ctor"); }
  42. ~this() { writeln("dtor"); }
  43. }
  44.  
  45. void main()
  46. {
  47. /* mallocated */
  48. Foo bar = o_new!Foo();
  49. writeln("some program");
  50. o_delete(bar);
  51. }
Success #stdin #stdout 0.01s 2120KB
stdin
Standard input is empty
stdout
ctor
some program
dtor