How to write a proper class destructor?
Bradley Smith
digitalmars-com at baysmith.com
Thu Jan 25 10:09:45 PST 2007
Jarrett Billingsley wrote:
> "Bradley Smith" <digitalmars-com at baysmith.com> wrote in message
> news:ep9joi$1mr2$1 at digitaldaemon.com...
>> According to the documentation, a class destructor is "expected to release
>> any resources held by the object."[1] However, if resources to be released
>> are in objects to be garbage collected, "those references are no longer
>> valid."[1]
>>
>> How is a class supposed to release something for which it no longer has a
>> valid reference?
>
> Huuaaaahhh!
>
> I remember someone suggesting that 'scope' be a valid modifier for class
> instance variables, and it'd basically mean "when this class gets destroyed,
> destroy this other instance as well." Like auto-deletion when you use a
> scope reference in a function:
Is scope a valid modifier for a data member? The documentation states
"scope cannot be applied to globals, statics, data members, inout or out
parameters".[2] In my tests, using scope on a data member compiles, but
doesn't change the behavior.
>
> class ResourceHolder
> {
> scope SomeResource mRsrc;
>
> this(char[] name)
> {
> mRsrc = new SomeResource(name);
> }
> }
>
> ..
>
> {
> scope holder = new ResourceHolder("a.file");
> ...
> } // holder is destroyed here, and so is its mRsrc member.
>
> Another solution would be to change the behavior of the GC so that deletion
> on program end _is_ deterministic. That is, it'd basically run a collection
> sweep, call finalizers on objects which don't have references to them, and
> keep doing that until nothing is left. That way, references to other
> classes would always be valid in destructors, since the GC wouldn't collect
> those references until everything that points to them is destroyed.
>
Are you saying that a proper class destructor can't be written without
modifying the language?
Thanks,
Bradley
[2] http://www.digitalmars.com/d/attribute.html#scope
More information about the Digitalmars-d-learn
mailing list