Microsoft objects, the Release() functions return value?
Asked Answered
J

3

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

Jeffereyjefferies answered 20/5, 2009 at 15:35 Comment(0)
T
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.

Tenerife answered 20/5, 2009 at 15:41 Comment(0)
J
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.

Jawbone answered 20/5, 2009 at 15:45 Comment(0)
T
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.

Tenerife answered 20/5, 2009 at 15:41 Comment(0)
C
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; 
Cotten answered 20/5, 2009 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.