Resource Management... Howto?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Sat Jul 7 09:30:48 PDT 2007
"Samuel Winchenbach" <swinchen at eece.maine.edu> wrote in message
news:f6o2k2$2gu6$1 at digitalmars.com...
> class TextureHandle
> {
> private Texture mTexture;
> private char[] mName;
> this(texture aTexture, char[] aName)
> {
> mTexture = aTexture;
> mName = aName;
>
> }
> ~this()
> {
> mTexture.mRef--;
> if (mTexture.mRef == 0)
> {
> mTexture.freeGPUtexture();
> textureList.remove(aName);
> delete mTexture;
> }
> }
>
> }
The only issue with this is that _technically_ what you're doing in the
destructor is illegal. Destructors of non-scope classes aren't guaranteed
to be called (i.e. on program exit, they might not be, but the GC will
definitely call them). Furthermore, the order of destruction is undefined,
meaning that on program exit, mTexture might be destroyed before this,
causing a nasty access violation when you try to do "mTexture.ref--".
However, you can avoid this ugly nondeterministic-ness by always using scope
references to TextureHandle (you can have scope references to non-scope
classes, too), or by keeping all instances of TextureHandle in a
static/global list which you clean up in a "static ~this()" -- when static
dtors are called, the GC has not yet cleaned up, so it's still legal to
access reference members in class dtors.
More information about the Digitalmars-d-learn
mailing list