Object cleanup and weak references

Lionello Lunesu lionello at lunesu.remove.com
Sun Oct 29 00:55:51 PDT 2006

"Max Bolingbroke" <"batterseapower{no"@sp4/\\/\\}hotmail.com> wrote in 
message news:ei0dnr$lv$1 at digitaldaemon.com...
> Hi,
> I was writing a thin wrapper for SDL in D, in which I hoped to do 
> something like the following (very much simplified from real code):
> static this()
> static ~this()
> { SDL_Quit(); }
> class Surface()
> {
> SDL_Surface* handle;
> public this(char[] filename)
> { handle = IMG_Load(filename); }
> ~this()
> { SDL_FreeSurface(handle); }
> }
> It looks great and I don't have to remember to explicitly free my 
> surfaces. However, there are two problems with Ds shutdown process that 
> mean this won't work:
> 1) In my case the static constructor / destructors were located in a 
> separate "initialize" module, and it turned out that on quit it was being 
> destructed (running SDL_Quit) BEFORE the GC ran and destructed my Surface 
> objects (running SDL_FreeSurface). Clearly we can't Free after we have 
> Quit, so that's problem number 1.

You can force the GC to run a collect: std.gc.fullCollect();
Try doing that in the static ~this. Of course, if there are any pointers (or 
values looking like pointers!) in memory pointing to a surface object, that 
object would still not get deleted, causing an exception.


More information about the Digitalmars-d-learn mailing list