Microsoft objects, the Release() functions return value?

怎甘沉沦 提交于 2019-12-05 08:29:51

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.

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.

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; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!