Game Development Reference
In-Depth Information
object if the counter drops to zero. A shared object can have multiple references safely
without fear of the object being destroyed, leaving bad pointers all over the place.
Use AddRef() and Release() with Caution
Good reference counting mechanisms automatically delete the object when the
reference count becomes zero.
If the API
leaves the explicit destruction of the
object to you, it
all you have to do is forget to
call Release() . You can also cause problems if you forget to call AddRef()
when you create the object.
'
s easy to create memory leaks
s likely that the object will get destroyed
unexpectedly, not having enough reference counts.
It
'
Any time you assign a pointer variable to the address of the reference-counted object,
you
'
ll do the same thing. This includes any calls inside a local loop:
for (int i=0; i<m_howMany; ++i)
{
MySound *s = GoGrabASoundPointer(i);
s->AddRef();
DangerousFunction();
if (s->IsPlaying())
{
DoSomethingElse();
}
s->Release();
}
This kind of code exists all over the place in games. The call to DangerousFunc-
tion() goes deep and performs some game logic that might attempt to destroy the
instance of the MySound object. Don
t forget that in a release build the deallocated
memory retains the same values until it is reused. It
'
s quite possible that the loop will
work just fine even though the MySound pointer is pointing to unallocated memory.
What
'
s more likely to occur is a terrible corruption of memory, which can be
extremely difficult to track down.
Reference counting keeps the sound object around until Release() is called at the
bottom of the loop. If there was only one reference to the sound before the loop
started, the call to AddRef() will add one to the sound
'
s reference count, making
two references. DangerousFunction() does something that destroys the sound,
but through a call to Release(). As far as DangerousFunction() is concerned,
the sound is gone forever. It still exists because one more reference to it, through
MySound *s , kept the reference count from dropping to zero inside the loop. The
final call to Release() causes the destruction of the sound.
'
 
Search WWH ::




Custom Search