Destructor called while object is still alive

Guillaume Piolat first.name at guess.com
Sun Oct 25 22:15:05 UTC 2020


On Sunday, 25 October 2020 at 15:50:36 UTC, Steven Schveighoffer 
wrote:
> But even if you have synchronous management of files, having a 
> destructor clean up a file that obviously isn't used any more 
> isn't a bad thing.
>
> -Steve

The real problem with coincidental correctness comes when your 
resource dependency graph gets more complex.

The typical example is:

   1. You've loaded a library upon which all library object 
depend, you get a handle H to be released with releaseH(H). You 
put it in a class.

   2. This handle H allows you to create a library object A, to be 
released with releaseA(H, A). A cannot be released if the library 
has been released. So In A you keep a reference to H so that it's 
not cleared by the GC ; else you can't call releaseA(H, A) in A's 
destructor. The problem is that A is polymorphic, so it can't be 
a struct.

   3. Your A goes out of scope at the end of the program, the GC 
"chooses" to call H destructor first, and then A's destructor, 
where the H member is dead. The user end up with the conclusion: 
"the GC has collected a live object".
      However at first you don't see the bug because up to know 
A's destructor was called first.









More information about the Digitalmars-d mailing list