class destructors must be @disabled?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed May 18 18:56:15 UTC 2022


On Wed, May 18, 2022 at 11:02:01AM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
[...]
> HORROR:
> 
> Now, a big one that I've just realized.
> 
> - The two guidelines above (the "don't touch class members" one and
> the "don't allocate" one) miss an important fact that they apply
> recursively even to struct members of classes. For example, structs
> that are used as members of a class cannot allocate memory in their
> destructors either.
[...]
> Of course, we still should and do have the power to shape our programs
> any way we want but I think '@disable ~this();' should be added to
> classes as a general rule unless the programmer knows it will work
> otherwise.
[...]

I remember years ago, Andrei proposed that we remove class dtors (or
finalizers, whatever) from the language altogether.  That may be a bit
extreme, but it reflects the general idea you wrote here.

One observation about class dtors is, if they're useless for cleaning up
resources (since we can't rely on them being run at all, and we're not
allowed to touch anything referenced by the class that may have already
been collected by the GC, and we're not allowed to do anything that may
trigger a GC allocation), then *what practical use do they serve at
all*?!  At this point they're just some vestigial construct that are not
useful for all practical intents and purposes anymore.

The one big caveat, of course, is emplaced classes and classes whose
allocation is being managed by something other than the (default) GC. If
a class is stack-allocated, for example, the dtor could meaningfully do
something useful like free resources upon going out of scope.  IOW,
class dtors are useless by default, and only useful in non-default
usage. :-P


T

-- 
Obviously, some things aren't very obvious.


More information about the Digitalmars-d-learn mailing list