1 /** Memory management in better C. 2 * 3 * See_Also: https://lsferreira.net/posts/zet-1-classes-betterc-d/ 4 */ 5 module nxt.bcmm; 6 7 T alloc(T, Args...)(auto ref Args args) 8 { 9 enum tsize = __traits(classInstanceSize, T); 10 T t = () @trusted { 11 import core.memory : pureMalloc; 12 auto _t = cast(T)pureMalloc(tsize); 13 if (!_t) return null; 14 import core.stdc.string : memcpy; 15 memcpy(cast(void*)_t, __traits(initSymbol, T).ptr, tsize); 16 return _t; 17 } (); 18 if(!t) return null; 19 t.__ctor(args); 20 21 return t; 22 } 23 24 void destroy(T)(ref T t) 25 { 26 static if (__traits(hasMember, T, "__dtor")) 27 t.__dtor(); 28 () @trusted { 29 import core.memory : pureFree; 30 pureFree(cast(void*)t); 31 }(); 32 t = null; 33 } 34 35 version (unittest) 36 { 37 extern(C++) class Foo 38 { 39 this(int a, float b) 40 { 41 this.a = a * 2; 42 this.b = b; 43 } 44 int a; 45 float b; 46 bool c = true; 47 } 48 49 extern(C) int test() 50 { 51 Foo foo = alloc!Foo(2, 2.0f); 52 scope(exit) destroy(foo); 53 54 int a = foo.a; // 4 55 float b = foo.b; // 2.0 56 bool c = foo.c; // true 57 58 return 0; 59 } 60 }