2

What's the use of the static_cast<IDropSource*> in this piece of code (taken from here):

HRESULT CDropSource::QueryInterface(REFIID riid, void **ppv){
    IUnknown *punk = NULL;
    if (riid == IID_IUnknown) {
        punk = static_cast<IUnknown*>(this);
    } else if (riid == IID_IDropSource) {
        punk = static_cast<IDropSource*>(this);
    }
    
    *ppv = punk;
    if (punk) {
        punk->AddRef();
        return S_OK;
    } else {
        return E_NOINTERFACE;
    }
}

I fail to see what's the purpose of casting this to IDropSource* if it's going to be assigned to a variable of type IUnknown*.

Does this make any difference when later calling punk->AddRef()?

Seth
  • 83
  • 7
  • Ah... sorry I'm blind. – Passer By Mar 12 '22 at 14:03
  • 1
    There is no underlying reason; it's no-brainer coding logic: if (riid == IID_XXX) then the pointed-to type is XXX. That IDropSource inherits from IUnknown here is intellectual baggage that is left to the compiler to work out. This is a typical example of optimizing for code writing instead of code reading. Don't write code like that (also never learn C++ coding style from Microsoft). – rustyx Mar 12 '22 at 14:36
  • This could somehow be taking advantage of UB to allow compiler optimizations? I'd need someone else to tell me where, but that's my best guess if this code does anything aside from being boilerplate. – JohnFilleau Mar 12 '22 at 14:49
  • @rustyx Perhaps the reason is the same as mentioned [here](https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/special-issue/c-visual-c-2015-brings-modern-c-to-the-windows-api)? Quoting: _"The cast merely adjusts the pointer to find the correct location in the class vtable, and because all interface vtables start with `IUnknown`'s three methods, this is perfectly valid."_ — but in that case, I think the result of the cast should be assigned to `*ppv` directly, not to `punk`. I find it unlikely that Raymond Chen would write a code with no underlying reason at all. Just a typo maybe? – heap underrun Mar 12 '22 at 20:36

0 Answers0