为什么这个COM IUnknown :: Release的实现工作? [英] Why does this implementation of COM IUnknown::Release work?

查看:457
本文介绍了为什么这个COM IUnknown :: Release的实现工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从示例中我看到COM IUnknown :: Release()函数实现是这样的:

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

因此,如果m_count为0, ,并返回引用计数。
我不明白是为什么它工作原理?!?

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. 删除对象不会毁了因为它是由线程持有的,所以它与对象无关。

  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 ???

如果对象有被删除,我们怎么可能返回m_count,它应该已经被删除。我可以说服自己,如果删除后的代码将返回硬编码0,但它怎么可以返回成员呢?没关系。

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! :-)

推荐答案

这段代码是假的。人们永远不会信任减少后的 之后的m_count。正确的代码是总是,如下所示:

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

这篇关于为什么这个COM IUnknown :: Release的实现工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆