Jarrett Billingsley Wrote:

> On Fri, Aug 7, 2009 at 1:20 PM, Aaron Watters<arw1...@yahoo.com> wrote:
> > Hi guys.  D looks cool.  A couple of things confuse me.
> > The first is: what happens if I do a
> >
> > delete cl;
> >
> > after storing a reference to cl somewhere?  Can I use the stored
> > reference?  Is it invalid?  Please elucidate, thanks.
> 
> If you delete something and attempt to use another reference to the
> deleted object, the behavior's undefined.  Basically the same thing as
> accessing a dangling pointer in C or C++.  'delete' is really just
> there for when you *know* that there are no other references and you
> want to ensure that it gets cleaned up immediately.

If you're interested in how this behaves in the runtime, "delete cl;" tells the 
memory manager to reclaim the memory at 'cl'. It does so by putting its block 
of data back onto its internal freelist. At that point the first 4 bytes are 
used in a linked list. If you still have references to that memory and then 
modify it, you break the memory manager internal state, which is gonna be hard 
to track back. After the memory has been reallocated, your old reference and 
the new one are now fighting for the same memory block. In either cases, your 
old reference will cause trouble that will be very hard to isolate.

A good rule of thumb in D is that if you're unsure whether references are still 
alive, don't delete the object, the GC will automatically reclaim the memory 
once it detects there are no more references to it. It is also faster to go 
that way, lots of delete calls are more expensive than one GC sweep, and the 
sweep is going to happen sooner or later anyways.

However, delete is most useful when you need large blocks of data for short 
periods of time.

Reply via email to