when is the object destuctor called?

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon May 22 08:59:14 PDT 2006


"Johan Granberg" <lijat.meREM at OVEgmail.com> wrote in message 
news:e4sj2e$43o$1 at digitaldaemon.com...

> This made me wonder in what circumstances the destructor WONT bee called.

That's a bit difficult.  If you do something like this:

Crap c;

class Crap
{
 this()
 {
  writefln("ctor");
 }

 ~this()
 {
  writefln("dtor");
 }
}

static this()
{
 c = new Crap();
}

void main()
{

}

The dtor is never called.  It seems that any kind of global or static 
references (kept like this or kept in arrays / AAs) are never collected at 
the end of a program - this seems to be a bug.  It might not be, though, as 
Walter has said before that he doesn't believe that dtors should be called 
at the end of the program, as the OS will reclaim all the memory for the 
objects anyway.  I call this BS, as any non-trivial program will hold 
resources _other_ than memory, and will have to release external resources 
(like video resources, file handles, databases, etc).  In this case, he says 
to use RAII, but that's not a solution to things like this.

But if you call "delete" on an object, the dtor is called _right then_. 
Which is how I solved the problem.


> Basically I want to do this: An object stores a OpenGL texture (uint) and 
> when the object gets collected/deleted I want to free the texture. I don't 
> care about if the destructor will bee called on program exit, but I need 
> some mechanism for freeing the textures during normal execution to prevent 
> a video memory leak.
>
> So I need to know if I can trust the destructor to do this or it their is 
> some other mechanism I can use.

I do a very similar thing, but in DirectX instead of OpenGL.  Basically, I 
keep an AA of all the instances of a resource-holding class (such as a 
texture class):

class Texture
{
    this()
    {
        // acquire texture interface
        textures[this] = this;
    }

    ~this()
    {
        // release texture interface
        textures.remove(this);
    }

    static Texture[Texture] textures;
}

Then, I have a static dtor which loops through all the textures and deletes 
them.

static this()
{
    foreach(Texture t; textures)
        delete t;
}

All instances are deleted.

This works well, and if the GC behavior is ever changed, this mechanism will 
still work. 





More information about the Digitalmars-d mailing list