Question

If I have a D object, how can I destroy that D object from the inside? (Have it destroy itself)

class A {
    public void destoy() {
        // Destroy me! 
    }
}

A a = new A;
a.destroy();
Was it helpful?

Solution

No, there is no way to do this in D, and there are good reasons for it. This SO thread explains how it can be done in C++, and explains the threats of delete this ...

IMHO, it is a good idea D disallows this, because it seems logical - objects should not control their own lifecycle, program should do that. Program "gave life" to objects, program should "take their lives" (garbage-collect them in this case) too.

OTHER TIPS

Unfortunately, there is no way for an object to know about any external references to it.

To get around this, you can add a method that keeps track of fields storing pointers to the object. However, this is clunky, and results in trying to modify external data.

You could add a set of signals and slots to your object, enabling it to tell all who will listen that it wishes to be destroyed. However, this forces external code to add extra methods for each reference to your object they wish to use.

Hopefully there is a way to modify your algorithm such that it does not depend on getting garbage collected at an explicit time, or on generating dangling pointers, one of the problems that D is meant to eradicate.

Make it whatever you want to destroy equal to 'NULL' for example

class A {
    public void destroy() {
        state = NULL;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top