Destructors can't be @nogc?

Mike Parker aldacron at gmail.com
Sat Jul 24 10:15:50 UTC 2021


On Saturday, 24 July 2021 at 09:45:01 UTC, Jim wrote:

>
> In that case, what should we use to check functions called from 
> `main` are not using the garbage collector?

When compiling, you can pass -vgc to dmd and it will tell you 
where GC allocations are possible.

>
> Because it seems like we can't use classes with `@nogc`. We can 
> write `.deinit()` for all our classes but what about the 
> existing ones?

You're trying to shoehorn a GC-based feature into a no-GC world. 
It's possible, but it takes consideration of your overall 
architecture. If you're wanting to prevent GC usage in the entire 
program, then the easiest way is to avoid features that normally 
rely on the GC.

Consider if you really need classes. Can you just use malloced 
structs instead? If you do need classes, perhaps for inheritance, 
then scoped classes can be allocated on the stack where possible; 
then you get automatic destruction like structs. If you want to 
allocate them from the heap as in your example, then you can wrap 
instances in a ref-counted struct that calls a custom destructor 
(like your .deinit). You could also try marking your classes as 
extern(C++), then the GC isn't involved anyway.

There are many options, but in bypassing D's built-in automatic 
memory management, you're going to have to work for each of them 
to one degree or another.

Personally, I think `@nogc` on main is a bad idea. `@nogc` should 
be used as far down the call stack as you can put it. The higher 
it is, the more difficulty you're going to run into. I recommend 
you apply it only on functions that run in the hottest parts of a 
program. Those are the areas where GC allocations triggering 
collections can obviously become an issue. So start there.

If, down the road, you find that you've got some GC performance 
troubles outside of @nogc code, -dvst can help you find areas 
where you may be calling it unexpectedly and you can refactor 
those parts as needed and still do so without applying @nogc.

You can also look into disabling the GC at specific points and 
renabling later, or manually run collections at certain points. 
These are tools that are available that may or may not help.

You might get some ideas from the GC series on the blog:

https://dlang.org/blog/the-gc-series/

But if you really want to zap GC from the entire program, you're 
better of with -betterC. You aren't going to be using any 
GC-based features anyway, so why worry about @nogc? Everything is 
@nogc by default in betterC as the GC doesn't exist.




More information about the Digitalmars-d-learn mailing list