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

有些话、适合烂在心里 提交于 2019-12-04 05:23:59

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;
}
sharptooth

What you observe is undefined behavior. The call stack is not changed by delete this; and delete this by itself is always safe but renders this pointer invalid which means you can't dereference it anymore.

There're two possible explanations of what you observe. Either the implementation in question just doesn't dereference this pointer to obtain m_count when returning from the function - it has it loaded onto a register and just uses that value and so this is not dereferenced and you don't observe any problem or when delete finishes the memory occupied by the object is still mapped into the process address space and remains technically accessible and so dereferencing this succeeds and m_count is read successfully. I suppose the latter is more likely.

Whatever the explanation is that undefined behavior, you can't rely on that, use what user Remus Rusanu suggests in his answer.

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