Multiple destructors

Basile B. b2.temp at gmx.com
Fri May 26 10:28:16 UTC 2023


On Friday, 26 May 2023 at 09:07:07 UTC, Alex Biscotti wrote:
> Hello everyone! While researching the phobos library, I 
> discovered that a class can have multiple destructors if the 
> destructors are added via mixin injection. Accordingly, the 
> question is whether a description of such feature should be 
> added to the documentation, since the current description is a 
> bit confusing - ["There can be only one destructor per 
> class"](https://dlang.org/spec/class.html#destructors)?

This is not a compiler bug, mixin templates are allowed to 
introduce a dtor; observe the output of

```d
import std;

mixin template AddNewDtor()
{
     ~this()
     {
         writeln("Mixin dtor");
     }
}

class Foo
{
     ~this()
     {
         writeln("Class dtor");
     }

     mixin AddNewDtor;
}

void main()
{
     {
         Foo s = new Foo;
         writeln("-- dtor effect --");
         s.__dtor;
     }
     {
         Foo s = new Foo;
         writeln("-- xdtor effect --");
         s.__xdtor;
     }
     writeln("-- auto generated destruction... --");
}

```

as you can see, the internal `__xdtor` function is designed to 
call the two destructors, while `__dtor` only the "normal one", 
i.e the one that 's not mixed in.

This is more a documentation bug IMO.


More information about the Digitalmars-d-learn mailing list