Reddit: SafeD - The Safe Subset of D

Brad Roberts braddr at puremagic.com
Tue Mar 25 23:36:59 PDT 2008


Chris Miller wrote:
> Chris Miller Wrote:
>> http://www.digitalmars.com/d/2.0/class.html#Destructor
>>
>> "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."
> 
> Oh, well then you should just move the code you wanted to run in the parent object's destructor to the sub-object's destructor, though it does leave my wondering why the garbage collector would have killed the sub-object first, since if there is code in the parent object's destructor that uses the sub-object, that should count as a reference, so the sub-object should still be in scope - I think.  Or does code in a destructor not count towards keeping heap references in scope?
> 
> -- the "other" Chris Miller

'code' never holds references, strictly data.  The question you have, I
believe, is when obj1 holds a reference to obj2 (be it a pointer or a
reference), what happens when the last reference to obj1 disappears.
Both objects become 'dead' and the order of cleanup is undefined.  In
that case, you can question the choice, but consider any cycle of
references where together they are all referenced.  When the last
external reference to the cycle disappears the entire set is collectable
with no 'right' order.  Based on the fact that in some cases there's no
'right' order, the collector takes the approach of 'no order can be
assumed for any object being collected'.  The result being that no
references to other collectable memory can be referenced from a
destructor.  Because of the collector, you don't need to either.
Destructors only need to manage non-collectable entities.

Later,
Brad


More information about the Digitalmars-d-announce mailing list