How should class objects created in betterC be destroyed

Paul Backus snarwin at gmail.com
Mon Nov 6 17:42:01 UTC 2023


On Monday, 6 November 2023 at 05:30:02 UTC, zoe wrote:
> I customized object.d in -betterc mode and created NEW 
> templates, with modules I can seemingly create classes without 
> extern(C++) mode, and type conversions in function calls seem 
> to work fine. But when destroy doesn't find a way to call the 
> __xtdor() method of the corresponding subclass, is there any 
> way to execute __xtdor() correctly

Unfortunately, D classes cannot have virtual destructors, so 
TypeInfo is the only way to find the correct derived class 
destructor to call at runtime.

I think the best you can do is implement your own virtual 
destructors, and your own `destroy` function that knows how to 
call them; for example:

```d
interface BettercDestructible
{
     void destruct() nothrow @nogc;
}

class MyClass : BettercDestructible
{
     // ...
     override void destruct()
     {
         // destructor implementation here
     }

     ~this() { this.destruct(); }
}

void destroy(BettercDestructible obj)
{
     obj.destruct();
}
```

Of course, for classes that don't implement 
`BettercDestructible`, you're still out of luck, but it's better 
than nothing.


More information about the Digitalmars-d-learn mailing list