destructors

Bill Baxter dnewsgroup at billbaxter.com
Tue May 1 17:01:02 PDT 2007


Daniel Giddings wrote:
> Daniel Keep wrote:
>>
>>
>> Exactly.  You can't.
>>
>> Long story short is thus: the *only* thing you can say for sure still
>> exists when your destructor is called, is your own object's memory.
> 
> Yuck - I never really thought about this. So destructors in D are almost 
> as useless as the __del__ method in Python :-(
> 
>> Question: what order do the objects get destroyed in?
>> Answer: no one knows.
>>
>> The problem is that in order for the GC to destroy objects in "the right
>> order", it would have to build a complete dependency graph between the
>> various objects, then destroy them in the right order.
>>
>> But what happens if you've got a *lot* of objects, or those objects
>> don't care what order they're destroyed in, or worse: cycles.  If you've
>> got cycles, the GC is stuffed, and there *is* no correct order to
>> destroy them in.
>>
>> There was a thread quite some time ago that demonstrated a hacked
>> version of phobos that allowed destructors to take a bool argument that
>> told the destructor if the object was being destroyed deterministically
>> (ie: via the delete statement, or because the object was scoped) or not.
>>  Sadly, it never caught on :(
>>
>>     -- Daniel
>>
> 
> The bool would be incredibly handy as you'd be able to still do 
> destructor type things safely with explicit deletes.
> 
> I suppose an alternative would be something like
> 
> class MyClass
> {
>    OtherClass a;
>    this() { a = new OtherClass; }
>    MyClass destroy() { delete a; delete this; return null; }
>       // is the return null above ok in D? - it seemed ok when run
> }
> 
> then you'd know when its been explicitly deleted.
> 
> MyClass m = new MyClass;
> ...
> m = m.destroy();


I was thinking that too.  That might be ok for some use cases, but it 
doesn't help with 'scope' instances (the destructor will get called not 
your 'destroy()' method).  And in generic cases, like a tuple of objects 
you want to destroy, the generic function has no way of knowing that it 
should call 'obj.destroy()' on some objects instead of 'delete obj'.


--bb


More information about the Digitalmars-d-learn mailing list