Destructing Member Objects

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Apr 5 21:27:52 PDT 2008


"Lionello Lunesu" <lio at lunesu.remove.com> wrote in message 
news:ft9350$23n8$1 at digitalmars.com...
> Brian White wrote:
>> I understand that you're not supposed to delete member within the 
>> destructor because, when called via the GC, it's possible that object has 
>> already been destructed.
>
> :O really? Where can I find more information about this?
>
> I think it's odd that a member can get deleted before a class that 
> contains it. That class still has a valid pointer to it, right? So the GC 
> could not have finalized it.. ???
>
> L.

http://www.digitalmars.com/d/1.0/class.html#destructors

"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 are no longer valid. This means that destructors cannot reference 
sub objects. This is because that the garbage collector does not collect 
objects in any guaranteed order, so there is no guarantee that any pointers 
or references to any other garbage collected objects exist when the garbage 
collector runs the destructor for an object. 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 spec doesn't really specify _why_ destruction order is nondeterministic, 
however.  You need nondeterministic destruction in order to break cycles. 
So if A points to B and B points to A, you have a cycle.  In order to break 
the cycle you have to delete one or the other first.  There's no "correct" 
order to destroy them.  So, to solve this, you simply cannot guarantee that 
when an object's destructor is run, that everything that it points to is 
still valid.

(Note, however, that system resources (file handles, Windows COM interfaces, 
sockets, things like that) _can_ be referenced since they weren't allocated 
on the GC heap.  The only problem there is _when_ they're referenced, since 
there's no guarantee that the object containing the reference to the system 
resource will be collected in any timely fashion.) 




More information about the Digitalmars-d-learn mailing list