Question about COM Release () Method

I am learning COM and reading about this code:

    STDMETHODIMP_ (ULONG) ComCar::Release()
{
   if(--m_refCount==0) delete this;
   return m_refCount;
}

My question is: if m_refCount == 0 and the object is deleted, how can the m_refCount variable of the instance member exist and be returned? Please forgive me if my question is so naive because I am completely new to COM. Many thanks.

Related thread here: How does a member method delete an object?

+5
source share
2 answers

Your problem is correct, the reference count must be moved to 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 this code is still erroneous because it is not thread protected.

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);
  }
+6
source

, m_refCount?

, - undefined , .

, , - Release() , .

+1

All Articles