vestigial delete in language spec

Jonathan M Davis jmdavisProg at gmx.com
Thu Nov 1 16:11:18 PDT 2012


On Thursday, November 01, 2012 22:21:11 Dan wrote:
> struct S {
> int[] a; // array is privately owned by this instance
> this(this) {
> a = a.dup;
> }
> ~this() {
> delete a;
> }
> }
>
> Is the delete call, then per TDPL not necessary? Is it harmful or
> harmless?

It's not necessary at all. delete is _never_ necessary, and it's not safe. 
delete frees GC-allocated memory. If you just leave it alone, and there are 
really no other references to it, then the GC will eventually free it if it 
needs more memory. Deleting it makes it so that it's freed now rather than 
freed who-knows-when later, but if any other references to that data still 
exist when it's deleted, then they'll end up pointing to garbage behavior, 
giving you nasty bugs.

Because of all of this, delete is going to be deprecated if it hasn't been 
already. core.memory will still provide functions for freeing GC memory if you 
really want to and are willing to go the extra mile to make sure that your 
code is safe, but there will no longer be a language primitive for doing so.

clear (which was recently renamed to destroy) specifically destroys an object 
but does _not_ free its memory. So, you won't end up with bugs due to other 
references to that data operating on garbage. In the case of classes, because 
destroy zeroes out the vtbl, calling virtual functions on the destroyed object 
will cause a segfault. In the case of primitives such as int, I believe that 
they're set to their init property. And in the case of arrays, I believe that 
it's no different from setting them to null, so nothing else is actually 
affected by calling destroy on them. Regardless, with destroy, you're not going 
to run into nasty memory issues due to memory being freed when other 
references to it still existed, because it doesn't actually free any memory. 
It just destroys what's there so that fewer references to it exist and so that 
any non-GC-allocated resources which the destroyed object had get released.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list