What's the use case of clear?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Aug 10 10:46:31 PDT 2010
On Tue, 10 Aug 2010 13:16:31 -0400, Jonathan M Davis
<jmdavisprog at gmail.com> wrote:
> On Tuesday, August 10, 2010 08:09:13 Steven Schveighoffer wrote:
>> But we should clarify a couple things. First, destructors are *only*
>> valid for releasing resources not allocated by the GC. For example, in
>> your Connection object, if you used a phobos object to make the
>> connection, and allocated that connection via new, then you are *not*
>> guaranteed that the GC hasn't collected that object already. So it is
>> not
>> valid in the destructor.
>
> Hmm. I don't recall ever reading that anywhere. I would not have expected
> anything that was referenced by an object to be garbage collected until
> the
> destructor had been called on that object. Granted, the need for
> destructors on
> classes is minimal, but that seems like the kind of thing that should be
> in big
> red lettering somewhere. You just know that there are going to be plenty
> of
> programmers out there who are going to referencing newed data in the
> destructor.
> It's a very natural thing to do for cleanup if you have object
> references as
> member data.
Yes, it is a common source of confusion to new programmers.
From this page: http://digitalmars.com/d/2.0/class.html#destructors
"The garbage collector is not guaranteed to run the destructor for all
unreferenced objects. Furthermore, the order in which the garbage
collector calls destructors for unreference objects is not specified. 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."
The second part that says when you delete it manually, the references are
still valid is meaningless. You only get one destructor, and it's not
notified whether its the GC calling it or delete/clear calling it. So if
you write your destructor to cater to manual deletion, the program may
crash if the GC destroys it.
Rule #1, destructors are only for non-GC allocated resources. With GC
allocated resources, you have to assume they are invalid in the
destructor. Always.
-Steve
More information about the Digitalmars-d
mailing list