Class destructors - clarify what is safe

H. S. Teoh hsteoh at qfbox.info
Sat Feb 14 21:15:25 UTC 2026


On Sat, Feb 14, 2026 at 08:49:08PM +0000, Brother Bill via Digitalmars-d-learn wrote:
> On Saturday, 14 February 2026 at 18:42:21 UTC, H. S. Teoh wrote:
> > Basically, when something is allocated on the GC, the GC takes full
> > responsibility for managing its lifetime. User code should not try
> > to intervene.  If your object needs to be managed manually, don't
> > allocate it from the GC, use C's malloc() or your own memory
> > allocation scheme.  Because of this, class dtors really should not
> > be necessary if you only allocate objects from the GC.  They are
> > only necessary when you need to manage resources that are not
> > allocated by the GC, such as OS file handles, memory allocated by
> > C's malloc(), or other such things.  The dtor should only take care
> > of cleaning up these external resources, and should not try to do
> > anything related to GC-allocated objects.
[...]
> How does one go about determining if these are GC-allocated objects,
> or if these are external to the GC?

You, the programmer, should know. :-D  If you used `new` to allocate
them, then they're allocated by the GC. Or if you used GC.malloc or any
of the GC methods from core.memory.GC.

If you allocated the objects using C's malloc(), then it's not
GC-allocated.  If it's a handle returned to you by the OS, then it's not
GC-allocated.  Etc.


T

-- 
Winners never quit, quitters never win. But those who never quit AND never win are idiots.


More information about the Digitalmars-d-learn mailing list