Re: stroustrup, void*, and reinterpret_cast
Dilip wrote:
ISomeInterface* isi;
CoCreateInstance(......,...., reinterpret_cast<void**>(&isi));
I believe you need more than the Standard guarantees for this to work.
A more conformant way would be
void* out_param;
CoCreateInstance(......,...., &out_param);
if (/* co-create succeeded */)
{
ISomeInterface* isi = static_cast<ISomeInterface*>(out_param);
// code using isi here
}
It also means you can't accidentally forget the & operator.
Internally a lot of hocus-pocus happens and the API ends up calling an
implementation of a standard IUnknown method called QueryInterface that
returns a pointer to ISomeInterface like so:
class SomeInterfaceImpl : public ISomeInterface
{
void QueryInterface(REFIID riid, void** ppv)
{
*ppv = static_cast<ISomeInterface*>(this);
reinterpret_cast<IUnknown*>(*ppv)->AddRef();
}
// remaining implementations elided for clarity
};
Don't all interfaces inherit IUnknown? If so, the reinterpret_cast
isn't needed at all (or a static_cast could be used just in case AddRef
has been hidden by ISomeInterface).
What I've said only addresses the casts used in a COM-like system. If I
remember correctly, to create real COM classes in C++, the compiler
needs to lay out the objects in a particular way. I've mostly seen
C-style casts in COM code; these work because of the extra requirements
COM places on the compiler's ABI. (You can create COM classes on other
compilers, but COM features won't map to C++ features. For example,
you'd have to create your own v-tables - that's how you write COM
classes in C).
James
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]