Question about COM Release() method
c++, com
Solution
Your concern is valid, the ref count should be moved into a local variable before the object is deleted.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
ULONG refCount = --m_refCount; // not thread safe
if(refcount==0) delete this;
return refCount;
}
But even that code is still wrong because it's not thread safe.
you should use code like this instead.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
LONG cRefs = InterlockedDecrement((LONG*)&m_refCount);
if (0 == cRefs) delete this;
return (ULONG)max(cRefs, 0);
}
Problem
I am learning about COM and reading about this code: ``` STDMETHODIMP_ (ULONG) ComCar::Release() { if(--m_refCount==0) delete this; return m_refCount; } ``` My question is, if the m_refCount==0 and the object is deleted, how could the instance member variable m_refCount still exist and be returned? Please forgive me if my question is so naive cause I am a totally newbie on COM. Many thanks. A related thread is here: How could a member method delete the object?