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