Microsoft objects Release () function return value?

I am curious because I could not find out about this on MSDN. I found that the Release() function is present in various COM objects, which I obviously should use to remove pointers. But I'm not sure if this exactly returns? I used to think that it would return the number of links that still exist for the remaining object, so something like:

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

Is it obvious to free all references to this pointer?

Or am I not seeing anything?

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

+6
c ++ pointers directx com reference-counting
source share
3 answers

Your theory is correct. COM memory management is based on reference counting. The Release method of the IUnknown interface will decrease the reference count and return it. This function will not release links. He does not know who owns the link. It simply decreases the reference count until it reaches zero, and then the object is destroyed. This is dangerous because others may still refer to it, which after the destruction of the object will become invalid.

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

+10
source share

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

Looping to Release () returns 0, definitely a mistake - you should never release links that you don't own.

+11
source share

Release () will return the current reference count of the object. But you should not do:

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

This will make a zero count and destroy the object.

In COM, a simple rule of thumb is that each AddRef () method must have the corresponding Release () (only one).

Typically, the implementation of Release () would look like this:

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

All Articles