Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this implementation of COM IUnknown::Release work?

Tags:

c++

windows

com

From examples I've seen COM IUnknown::Release() function implementation is something like that:

ULONG Release()
{
    InterlockedDecrement(&m_count);
    if(m_count == 0) {
       delete this;
    }
    return m_count;
}

So, if m_count is 0, so we're deleting "this" object, and returning the ref count. What I don't understand is why it works ?!?!

  1. Deleting the object wouldn't ruin the call stack or is it okay because it is being held by the thread, so it has nothing to do with the object ???

  2. If the object has been deleted, how is it possible that we can return m_count, it should've been deleted. I could have convinced myself that it's okay if after the delete the code would return hard-coded 0, but how come it can return the member ?!?!

Thanks a lot for your help! :-)

like image 849
TCS Avatar asked Feb 01 '11 18:02

TCS


1 Answers

That code is bogus. One can never trust m_count after the decrement. The correct code is always like this:

ULONG Release()
{
     ULONG count = InterlockedDecrement(&m_count);
     if(count == 0){ delete this; }
     return count;
}
like image 180
Remus Rusanu Avatar answered Sep 20 '22 20:09

Remus Rusanu