Search code examples
windowscomcom-interopiunknown

Is it worth checking for null pointer in QueryInterface() implementation?


IUnknown::QueryInterface() is passed a void** parameter denoting an address where to put the retrieved interface.

STDMETHOD QueryInterface(/* [in] */ REFIID riid, /* [iid_is][out] */ void** ppvObject)

Should the implementation of QueryInterface() check this pointer for being null (and then immediately return E_POINTER) or just write there?

I've seen a lot of COM-related code and almost everywhere no check is performed. Hypothetically someone could of course pass null pointer as this parameter, but is such check really needed?


Solution

  • You (the caller) don't need to check the pointer for not being NULL.

    However, you should check the returned HRESULT. The method will return E_POINTER if the output pointer is NULL and E_NOINTERFACE if the interface is unsupported.


    The callee should check the pointer for not being NULL and return E_POINTER if it is NULL:

    MSDN: Return Value:

    This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise. If ppvObject is NULL, this method returns E_POINTER.