Resource Management... Howto?
Samuel Winchenbach
swinchen at eece.maine.edu
Sat Jul 7 18:09:31 PDT 2007
Jarrett Billingsley wrote:
> "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.
>
>
Ok... How do you learn these things? I have been referencing the
digitalmars docs and well.. it sort of seems incomplete.
Anyways here is my next attempt. I have to change it around and get rid
of the "loadTexture" function because that can not return scope classes,
which makes sense I suppose.
btw, thanks for the help! This is certainly and educational experience.
module texture;
import std.stdio;
scope class TextureHandle
{
private Texture mTexture;
private char[] mName;
this(char[] aName)
{
mName = aName;
if (auto t = (aName in textureList))
{
mTexture = *t;
}
else
{
mTexture = new Texture();
textureList[aName] = mTexture;
}
mTexture.mRef++;
}
~this()
{
mTexture.mRef--;
if (mTexture.mRef == 0)
{
mTexture.freeGPUtexture();
textureList.remove(mName);
delete mTexture;
}
}
}
private
{
Texture[char[]] textureList;
class Texture
{
private uint mRef = 0;
this()
{
}
~this()
{
}
void freeGPUtexture()
{
}
}
}
More information about the Digitalmars-d-learn
mailing list