c++memory-managementcomdirectxiunknown

Cast DirectX interfaces to IUnknown pointers


Having quite a few interfaces in my code, I wanted to encapsulate repeating Release code in another method and not in a macro because this is C++ and I hate using macros. My initial attempt was to write a method such as

void SafeRelease(IUnknown **ppInterface) {
    if(*ppInterface) {
        (*ppInterface)->Release();
        (*ppInterface) = nullptr;
    }
}

however applying this method to a IDirect3DSurface9 * e.g. like SafeRelease(&mySurface) yields the error IDirect3DSurface9 ** is incompatible with IUnknown **.

  1. What am I doing here wrong?
  2. Is there a better approach (hopefully not using macros) to implement such a function?

Solution

  • Here's my method:

    template <typename T> void SafeRelease(T*& ptr)
    {
        if(ptr)
        {
            ptr->Release();
            ptr = nullptr;
        }
    }
    

    Example usage:

    IDirect3DDevice9 *pD3DDevice = NULL;
    d3d->CreateDevice(..., &pD3DDevice);
    SafeRelease(pD3DDevice);
    

    You may inline this function if you want.