dynamic_cast一个COM对象到COM接口不会引用引用计数,是吗? [英] dynamic_cast of a COM object to a COM interface doesn't bump the reference count, does it?

查看:421
本文介绍了dynamic_cast一个COM对象到COM接口不会引用引用计数,是吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个C ++类,X,它实现COM接口IY和IZ,我有一个指针y到类型X的对象的IY接口,我这样做:

If I have a C++ class, X, which implements the COM interfaces IY and IZ, and I have a pointer y to the IY interface of an object of type X, and I do this:

IZ *z = dynamic_cast<IZ *> ( y );

这不会影响对象的引用计数,是吗?我不必做一个Release()来解决它,对吧?

That doesn't bump the object's reference count, does it? I don't have to do a Release() to account for it, right?

如果重要,我使用ATL / COM。

If it matters, I'm using ATL/COM.

我猜测答案是没有它不会引用引用计数,没有你不必Release(),但我想确保。

I'm guessing the answer is "no it doesn't bump the reference count, and no you don't have to Release()", but I want to make sure.

提前感谢。

推荐答案

COM对象的引用计数有人调用IUnknown :: AddRef()。 QueryInterface(),根据COM规则,因为它给出一个新的接口指针,内部调用AddRef()。

Reference counts for COM objects are incremented when someone calls IUnknown::AddRef(). QueryInterface(), according to COM rules since it gives out a new interface pointer, internally calls AddRef().

在你发布的代码,你不是调用AddRef ),并且你不调用任何可能调用AddRef()的函数,那么为什么你认为引用计数会增加?

In your posted code, you're not calling AddRef(), and you're not calling any function that might call AddRef(), so why would you think the reference count would be incremented?

尽管ATL / MFC对大脑有什么影响,但没有涉及到魔法。如果有疑问,你总是可以在VS中查看反汇编并逐步通过它,并且证明自己AddRef()没有被调用。

Despite what ATL/MFC does to one's brain, there is no magic involved. When in doubt, you can always view the disassembly in VS and step through it and prove to yourself that AddRef() isn't being called.

编辑:我想重申Dewfy说,不要这样做。使用QueryInterface()。或者CComQIPtr<>(如果真的必须)。

And I want to reiterate what Dewfy said, don't do this. Use QueryInterface(). Or CComQIPtr<> (if you really must).

进一步编辑:如果你使用CComPtr<并且减轻了确定适当的重新计数的许多负担。你应该考虑使用它们。

Further edit: If you use CComPtr<> and CComQIPtr<> then you don't have to call Release() and much of the burden of figuring out the proper ref-counting is alleviated. You should really consider using them.

这篇关于dynamic_cast一个COM对象到COM接口不会引用引用计数,是吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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