Does Release call on an Interface ensure that the COM Component is distroyed

StackOverflow https://stackoverflow.com/questions/23193492

  •  06-07-2023
  •  | 
  •  

سؤال

i am working on a issue where i see an intermittent crashes happening at the customer site, while code review, i found that we have written that some code in the destructor to free memory etc. but my question is when does this destruct-or gets called.

does it get called when the client call's Release on the interface. or how do we free resources consumed by an interface or when are we supposed to free those resources.

i know when the call to Relase returns "0" the COM calls the DllcanGetUnloadNow and it the dll is unloaded , what about freeing memory?

can anyone clarify

regards tom

هل كانت مفيدة؟

المحلول

Typically the implementing object's destructor is called from Release if the reference count has reached zero. That is something that is performed by the implementing object's implementation of Release.

So, a typical implementation of Release looks like this:

IFACEMETHODIMP_(ULONG) Release()
{
    ULONG cRef = InterlockedDecrement(&_cRef);

    if (!cRef)
        delete this;
    return cRef;
}

نصائح أخرى

Proper use of COM requires that certain laws about managing the object lifetime through reference counting.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms692481(v=vs.85).aspx

A single piece of code that does not follow this rule is sufficient to cause a crash.

Consumer of COM interface has no control over destruction of COM class/object. Consumer's responsibility is to accurately call IUnknown::Release once an interface pointer needs to be released. While returned zero is typically an indication of "last release, and destruction" of the object, this value is informational and does not guarantee object destruction. It is COM object responsibility to do proper freeing when there are no external references to the object exist.

The rest of destruction is the responsibility of COM object implementation. Once it detects it was released by everyone holding references, it typically does self-destruction, in simplest scenario. However, it does not have to be this way exactly. The object might have some background activity to extend lifetime, there are singletons and cached objects where there is certain logic to keep object alive etc.

Hence, troubleshooting destruction splits into proper interface reference counting (AddRef/Release) and checking COM server to properly shutdown activity in absence of consumers (including freeing memory and resources).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top