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 	enum tsize = __traits(classInstanceSize, T);
9 	T t = () @trusted {
10 		import core.memory : pureMalloc;
11 		auto _t = cast(T)pureMalloc(tsize);
12 		if (!_t) return null;
13 		import core.stdc.string : memcpy;
14 		memcpy(cast(void*)_t, __traits(initSymbol, T).ptr, tsize);
15 		return _t;
16 	} ();
17 	if(!t) return null;
18 	t.__ctor(args);
19 
20 	return t;
21 }
22 
23 void destroy(T)(ref T t) {
24 	static if (__traits(hasMember, T, "__dtor"))
25 		t.__dtor();
26 	() @trusted {
27 		import core.memory : pureFree;
28 		pureFree(cast(void*)t);
29 	}();
30 	t = null;
31 }
32 
33 version (unittest) {
34 	extern(C++) class Foo
35 	{
36 		this(int a, float b) {
37 			this.a = a * 2;
38 			this.b = b;
39 		}
40 		int a;
41 		float b;
42 		bool c = true;
43 	}
44 
45 	extern(C) int test() {
46 		Foo foo = alloc!Foo(2, 2.0f);
47 		scope(exit) destroy(foo);
48 
49 		int a = foo.a;   // 4
50 		float b = foo.b; // 2.0
51 		bool c = foo.c;  // true
52 
53 		return 0;
54 	}
55 }