What is legal in a destructor?

Sean Kelly sean at f4.ca
Tue Aug 29 08:56:45 PDT 2006

Lutger wrote:
> I'm having some trouble understanding exactly what is and what isn't 
> legal to do in a (non-auto) destructor. I'm thinking about these 
> specifically:
> - using the 'this' pointer as a parameter to make calls to another (from 
> another class or free) function.
> - calling member functions.
> - referencing delegates to member functions.

The three above things are only legal if the functions are final or if 
you can be certain you are calling them from the most derived class 
instance.  Otherwise, there is a possibility that you will be calling 
into an already destroyed portion of the object.  For example:

class C {
     ~this() { fn(); }
     void fn() { printf( "default impl\n" ); }

class D : C {
     this() { val = cast(int*)malloc(int.sizeof); *val = 5; }
     ~this() { free(val); }
     void fn() { printf( "%d\n", *val ); }
private int* val;

D d = new D;
delete d;

Here, C's dtor calls the virtual function fn, which attempts to print 
val after the memory allocated for val has been freed by D's dtor.  So 
the function may print garbage or you may get an access violation.

> - referencing data fields with types like int.

Should be fine.


More information about the Digitalmars-d-learn mailing list