Dynamic_cast of a COM object to a COM interface does not affect the reference count, does it?

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

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

      

It doesn't affect the number of object references, does it? I don't need to do Release () to account for it, right?

If it matters, I am using ATL / COM.

I am guessing the answer is "no, it doesn't crash the links, and no, you don't need to issue ()", but I want to make sure.

Thanks in advance.

+2


source to share


3 answers


The reference count for COM objects increases when someone calls IUnknown :: AddRef (). QueryInterface (), according to COM rules, since it issues a new interface pointer, internally calls AddRef ().

In your posted code, you are not calling AddRef (), and you are not calling any function that might call AddRef (), so why do you think the reference count will increment?

Despite what ATL / MFC does with one brain, there is no magic. When in doubt, you can always look at the stripping in VS and go through it and prove that AddRef () is not being called.



Edit: And I want to reiterate what Dewey said does n't do it . Use QueryInterface (). Or CComQIPtr <> (if you really should).

Further edit: if you are using CComPtr <> and CComQIPtr <> then you don't need to call Release () and much of the burden of calculating correct scoring will be reduced. You should really use them.

+3


source


dynamic_cast cannot be used for several reasons:

  • You don't know if RTTI supports
  • You are not sure if OLE is not creating a proxy for you.
  • ...


Use QueryInterface instead - that would do what you want.

Even if you are sure of the question above - casting does not change refcounter

+4


source


In C ++ Builder dynamic_cast

, the COM interface actually gets executed QueryInterface

. and the returned pointer, if QI succeeds, gets AddRef

' d.

Classes that implement COM objects have different vtable layouts for more general C ++ classes, so the C ++ style dynamic_cast

can't work; so I guess that is why C ++ Builder makes the QueryInterface more sane task.

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

I think the main answer is related to MSVC if dynamic_cast causes undefined behavior.

0


source







All Articles