when is the object destuctor called?

Tom S h3r3tic at remove.mat.uni.torun.pl
Tue May 23 02:30:00 PDT 2006


Derek Parnell wrote:
> I didn't mention 'GC'. I used the term 'dtor'. I do not equate the two
> pieces of functionality. 

And I never suggested equating them. Yet the discussion earlier touched 
the matter of whether the GC should call dtors and whether one should 
depend on dtors being called at program exit.

And you wrote:
> I use the same technique. The idea that the only resource a ctor/dtor 
> manages is RAM is plainly short-sighted.

I assumed (perhaps incorrectly) that you wanted to depend on the GC to 
call dtors of objects that manage other resources than just RAM.

So if this is not the case, do you suggest that global objects should 
have their dtors called at program exit ? /* allowing the 'auto' 
modifier for global objects would be an option to implement it  */



It's clear that dtors should be called when you explicitly delete 
objects, but in case of explicit memory management, I'd still desist 
from using dtors for releasing resources. Why ? Let's assume that an 
object of class Foo holds a reference to another object, Bar. You manage 
the Foo objects by always freeing them manually using the 'delete' 
keyword and each Foo deletes its Bar in the dtor. But what happens if 
you create a bug and some Foo isn't deleted explicitly but instead the 
GC gets it ? A Bar could be released earlier and a Foo's attempt to 
release it again might be deadly ;)
In such a case, I'd prefer using a separate release() function 
orthogonal to the dtor. The worst that could happen then would be 
resource leaks. But they are smaller evil than pseudorandom crashes.

Thus I consider dtors and the GC to be strongly related. IMO the dtor 
should only be used in auto classes and some marginal cases (e.g. when 
an object allocates some memory using malloc).


> The 'dtor' is deconstruction functionality which should complement the
> construction function.

Indeed, and it shouldn't manage any resources other than RAM unless the 
class is declared as auto.


> The 'GC' is a mechanism to collect 'garbage' RAM. 
> 
> They are not the same thing.

That's clear.


-- 
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/M d-pu s+: a-->----- C+++$>++++ UL P+ L+ E--- W++ N++ o? K? w++ !O 
!M V? PS- PE- Y PGP t 5 X? R tv-- b DI- D+ G e>+++ h>++ !r !y
------END GEEK CODE BLOCK------

Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d mailing list