dynamic_cast of a COM object to a COM interface doesn't bump the reference count, does it?

荒凉一梦 提交于 2019-12-02 02:16:27

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().

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?

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.

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

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 must not be used on multiple reasons:

  • You don't know if destination supports RTTI
  • You not sure if OLE doesn't create proxy for you
  • ...

Instead use QueryInterface - it would done what you want.

Even if you sure in question above - casting doesn't changes refcounter

In C++Builder, dynamic_cast on a COM interface pointer actually does QueryInterface. and the returned pointer, if the QI succeeds, gets AddRef'd.

Classes which implement COM objects have different vtable layouts to more general C++ classes, so a C++-style dynamic_cast cannot work; so I presume this is why C++Builder does the more sensible thing of doing QueryInterface.

(The original idea of COM was to generalize the C++ object model to be language-agnostic and to a binary standard; they renamed dynamic_cast to QueryInterface).

I guess the top answer is referring to MSVC, if dynamic_cast causes undefined behaviour.

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