On Sunday, 16 February 2014 at 02:57:25 UTC, Steven Schveighoffer wrote:

New is not the issue. The expectation, when I write my class, that it will be cleaned up by the GC, is the issue.

I remember this little nugget of paradox from the documentation of classes:

"This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects deleted with the DeleteExpression, as the destructor is not being run by the garbage collector, meaning all references are valid."

So if you can write your class such that it will always require manual deletion, it's OK to refer to other GC'd objects in the destructor. Otherwise, it's not. Oh, and the runtime doesn't tell you when you're in the GC :)

This leads us to the fun problem:

1. Without a GC, a destructor is REQUIRED to clean up owned resources that were (likely) malloc'd. 2. With a GC, a destructor is REQUIRED to NOT clean up owned resources that were GC'd.

How to write such a destructor?

In D1 Tango added a new method, "dispose", to Object. This method is called when an object is destroyed either when calling "delete" or when going out of scope for scope declared objects.

/Jacob Carlborg

Reply via email to