How to create nogc code?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 10 18:08:16 PDT 2016


On Monday, July 11, 2016 00:37:39 Adam Sansier via Digitalmars-d-learn wrote:
> Also, When dealing with a complex tree like structure, is there
> an easy way to recursively free it by free'ing all the sub
> elements?

When manually managing memory, you're dealing with basically the same
constructs that you would have in C/C++. I mean, you're even using the exact
same functions when you're dealing with malloc and free. So, ultimately,
something is going to have to free each of those nodes individually, just
like it would in C/C++, but it could be managed by destructors if RAII or
reference counting is being used, just like you would in C++.

> Also, since I'm dealing with simple structs and strings, maybe I
> more intelligent string type can be used? One that uses opAssign
> to do reference counting? I imagine that the only time there are
> issues is during assignment, in most cases?

Andrei is currently working a ref-counted string type that he's calling
RCStr that he wants to get into Phobos (or maybe druntime) once it's done,
and it would not only be reference counted, but it would have small string
optimizations. So, for code where that would work better than just using D's
built-in arrays, that will be an option. And you could certainly code up a
type yourself that wrapped whatever array type that you wanted so that it
was managed via malloc and reference counting rather than with the GC, and
the malloc-ed memory was encapsulated within that type.

For most code, the built-in arrays work very well though. So, while you may
very well be better of using a user-defined type that used malloc
internally, you might also be prematurely optimizing out of fear of the GC
as folks sometimes do. But not knowing what you're doing in detail, I
couldn't say.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list