Object destruction versus finalization

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 12 15:17:51 PST 2013


On Wednesday, November 13, 2013 00:07:12 Florian wrote:
> I understood very well, that the garbage collector is not
> guaranteed to run. However, it does not explain the segmentation
> fault in my example, does it?

You're getting a segfault, because you're using something which is on the GC 
heap - namely the Connection that you allocated with new. You can't do that in 
finalizer, because the GC can choose to free it before the finalizer even runs 
(this avoids issues with circular references). You can only access stuff in the 
finalizer which is part of the class (and not on the GC heap aside from the 
fact that the instance of the class is itself on the GC heap) or which is not 
managed by the GC at all (e.g. it was malloced, or it was some other sort of 
system resource that the GC doesn't manage).

If you want your Connection object to shutdown when it's collected, you're 
going to need to do that in its own finalizer, not in the finalizer of a class 
that's using it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list