TDPL: Manual invocation of destructor

Jonathan M Davis jmdavisprog at gmail.com
Mon Aug 9 16:57:12 PDT 2010


On Monday, August 09, 2010 16:40:23 Andrei Alexandrescu wrote:
> class File {
>      FILE * fp;
>      this() { fp = fopen("/tmp/temporary"); }
>      ~this() { fclose(fp); }
> }
> 
> The destructor does not test fp because it assumes it was opened.
> 
> Interestingly enough, by TDPL the code above is in fact invalid already.
> TDPL mentions that an object's lifetime starts as soon as it's been
> branded, which is before default construction. As a direct consequence,
> the destructor should be able to deal with an object stamped with all
> init values for all fields - in this case a null fp.

I would take that as an argument for making clear() set the object in the state 
prior to the constructor call. That state is supposed to be completely valid 
from a memory standpoint. True, it goes against class invariants, but it would 
make clear() function in a manner closer to the delete that some folks are 
looking for. Truth be told, I'd sooner argue for removing clear() entirely, 
forcing people to either call a specific method on the class in question to free 
up whatever resources that they're so interested in freeing up, or forcing them 
to just give up on trying to free them and let the garbage collector do its 
thing. But if there's enough demand for a function which destroys an object and 
puts it in some sort of state which won't have undefined behavior, then making 
clear() put the class in a pre-constructor state seems the best to me. It's at 
least closer to what the folks who want delete are looking for. Of course, they 
probably won't be entirely happy until they have the nuke() function that you 
mentioned earlier, but at some point you have to face the fact that you're 
dealing with a garbage collected langugage and let it do its thing unless you 
really need to manually manage memory (at which point you should manually manage 
memory rather than try to contort the garbage collector).

- Jonathan M Davis


More information about the Digitalmars-d mailing list