The D standard library is built on GC, is that a negative or positive?

Dom DiSc dominikus at scherkl.de
Wed Dec 14 09:03:58 UTC 2022


On Wednesday, 14 December 2022 at 08:01:47 UTC, cc wrote:
> I disagree with the majority opinion on this subject.
> How do you instantiate a class object in D using the GC?
> ```d
> new Foo;
> ```
> How do you instantiate one using malloc?  Something like:
> ```d
> import core.memory;
> import core.stdc.stdlib : malloc, free;
> import core.lifetime : emplace;
> T NEW(T, Args...)(auto ref Args args) /*@nogc (nope!)*/ if 
> (is(T == class)) {
> 	enum size = __traits(classInstanceSize, T);
> 	void* mem = malloc(size);
> 	scope(failure) free(mem);
> 	//throw OOMError.get("Out of Memory in NEW!"~T.stringof); // 
> wanna GC-allocate here? use a predefined object? or just ignore?
> 	return mem !is null ? emplace!T(mem[0..size], args) : null;
> }
> // and don't forget
> void FREE(T)(ref T obj) /*@nogc*/ if (is(T == class)) {
> 	if (obj is null) return;
> 	auto mem = cast(void*) obj;
> 	//debug if (!GC.inFinalizer && GC.addrOf(mem)) return;
> 	scope(exit) free(mem);
> 	destroy(obj);
> 	obj = null;
> }
> ```
Yes, but be aware that this kind of stuff is, what you would also 
need to do in C++ to make it more safe - but nobody does it 
because it's so awful.
And in D you almost never need this, because it is sufficient to 
turn off the GC only in your performance critical loops.
So you get the same performance and the same (or better) memory 
safety with only a tiny part of the hassle.


More information about the Digitalmars-d mailing list