Class destructors - clarify what is safe

Steven Schveighoffer schveiguy at gmail.com
Sun Feb 15 00:42:33 UTC 2026


On Saturday, 14 February 2026 at 17:36:32 UTC, Brother Bill wrote:
> On page 325 of Programming in D, we may have a single 
> parameterless destructor named ```~this()```.
>
> A class may have members of string, File, other classes, etc.
>
> When entering a class destructor, are any of the dynamically 
> allocated class members safe to read?  That is, can we expect 
> that a class instance entering its destructor is "fully 
> intact", satisfying all its invariants, and all member 
> variables have not undergone any destruction at this point?
>
> I would expect that a class with strings, FILE handles, etc. 
> would need these to do its housekeeping.  If we opened a file 
> in the constructor, we should be able to close the file in the 
> destructor.

The destructor of a class is basically for cleaning up non-GC 
resources. You do not need to (and should not) try to free GC 
resources in a class destructor (you have to be careful with 
struct dtors as well, as those can be on the heap).

> As we can explicitly call destroy() on a class instance 
> multiple times, do we need to be "careful" of only closing a 
> file once, rather than closing a file multiple times, if that 
> can cause issues.

In practice, any GC-allocated object which has a *direct* link to 
a non-GC resource (file descriptor, c-malloc'd data, etc) should 
clean up the resource. You should not go through a GC-allocated 
object unless you have pinned it. If you want reliable ordered 
cleanup, you should implement this separately. e.g. add a `close` 
method.

-Steve


More information about the Digitalmars-d-learn mailing list