7

I'm curious because I couldn't find out about this on MSDN. I've found the Release() function is present in various COM objects which I'm obviously supposed to use for deleting pointers. But I'm not sure what does it return exactly? I used to think it would return the number of references which still exist to the object remaining, therefore something like:

while( pointer->Release() > 0 );

Would obviously release all references to that pointer?

Or am I not seeing something?

*note I'm talking about this from the concept of the IDirect3DTexture9::Release() function

3 Answers 3

11

In addition to what Mehrdad said, the return value of Release is intended for debugging purposes only. Production code should just ignore it.

Looping until Release() returns 0 is definitely a bug - you should never release references you don't own.

10

Your theory is true. COM memory management is based on reference counting. The Release method of IUnknown interface will decrement the reference count and return it. That function will not release references. It doesn't know who holds the reference. It just decrements the reference count until it reaches zero and then the object will be destructed. It's dangerous as others might still hold a reference to it that will become invalid after object's destruction.

Thus, you should only call Release for each AddRef you had previously called.

6

Release() would return the current reference count of the object. But you shouldn't do:

while( pointer->Release() > 0 );

This will make the reference count zero and destroy the object.

In COM a simple thumb rule is every AddRef() there should be corresponding Release() (only one).

Normally Release() implementation would look like this:

int nCount = InterlockedDecrement(&this->m_cRef); //Decrement the ref count
if (nCount == 0) 
{
    delete this;
}
return nCount; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.