Search code examples
c++windowscom

Proper way of calling AddRef() inside QueryInterface() implementation


I found some implementation pattern of QueryInterface() along these lines:

// Inside some COM object implementation ...

virtual HRESULT __stdcall QueryInterface(REFIID riid, void **ppv)
{
    *ppv = /* Find interface ... */
    if (*ppv == nullptr)
        return E_NOINTERFACE;

    static_cast<IUnknown *>(*ppv)->AddRef();  // ###         
    return S_OK;
}

The line of interest is the one marked with the // ### comment.

Is calling AddRef() on the IUnknown static_cast-pointer really necessary? Or is it just useless boilerplate code?
In other words, would a simple AddRef() call (i.e. this->AddRef()) be just fine? If not, why?


Solution

  • Sure, you normally have only one AddRef() implementation so it doesn't matter how you call it. Note how the way the code uses ppv was the possible inspiration, it is typeless (void**) so a cast is needed. Maybe a tear-off would make you do this differently.