Don't expect class destructors to be called at all by the GC

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Feb 1 19:35:56 UTC 2018


On Wed, Jan 31, 2018 at 01:38:07PM +0000, Bienlein via Digitalmars-d-learn wrote:
> On Thursday, 21 December 2017 at 18:45:27 UTC, Adam D. Ruppe wrote:
> > On Thursday, 21 December 2017 at 18:20:19 UTC, H. S. Teoh wrote:
> > > When the scoped destruction of structs isn't an option,
> > > RefCounted!T seems to be a less evil alternative than an
> > > unreliable class dtor.  :-/
> > 
> > Alas, RefCounted doesn't work well with inheritance...
> > 
> > Though, what you could do is make the refcounted owners and borrow
> > the actual reference later.
> 
> Is there some summary of the things you have to be aware of when using
> the GC in D and not using the GC? I feel this would be very useful
> especially for people that are new to D or are not used to that kind
> of issues (because coming from a GCed language).

D was originally designed with a GC in mind, so if you're using the GC
and writing typical GC'd code, there's really not much to be aware of,
esp. if you're coming from a GC'd language.  The only time you have to
be actively concerned about the GC is if:

1) You're interacting with C code and passing pointers around. You may
need to hold on to a copy of pointers you pass to C, because the GC does
not know any pointer roots in C land, so it may wrongly collect
something that the C code still holds a reference to.

2) You're writing performance-sensitive code and profiling shows that
the GC is becoming a bottleneck.  The usual easy solution is to import
core.memory and make use of GC.disable, GC.collect, GC.enable at
strategic points in your code.

3) You need to do useful work in dtors, and/or need deterministic
destruction, which is fundamentally incompatible with the GC.  In this
case, probably your best bet is RefCounted or some other kind of non-GC
memory management scheme.  Lately I'm beginning more and more to just
avoid class dtors in general, due to their inherent unreliability, and
just use scoped destruction (structs with dtors), or RefCounted, or some
other memory management scheme (perhaps raw malloc/free if I need tight
control over things).


T

-- 
VI = Visual Irritation


More information about the Digitalmars-d-learn mailing list