Handling CoCreateInstance return value

后端 未结 2 565
后悔当初
后悔当初 2021-01-19 14:15

Here\'s a code sample creating a COM object:

CComPtr pFilter;
auto hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL,
    CLSCTX_INPROC_S         


        
2条回答
  •  感情败类
    2021-01-19 14:36

    Having S_OK result from CoCreateInstance you are guaranteed to get a non-NULL interface pointer, so you don't need to check it additionally. To make it more reliable and be able to detect issues early, you might want to use ATLASSERT there to compare against NULL. This does not produce code in release builds, but generates an early warning in debug if anything goes wrong (esp. you edit or copy paste code later and change the logic of obtaining the pointer.

    CComPtr pFilter;
    HRESULT hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL, CLSCTX_INPROC_SERVER,
      IID_IBaseFilter, reinterpret_cast(&pFilter));
    if(SUCCEEDED(hr))
    {
      ATLASSERT(pFilter); // hr is of the interest because might explain failure
                          // pFilter is expected to be non-NULL in case of S_OK
      const CComQIPtr pDmoWrapperFilter = pFilter;
      if(pDmoWrapperFilter)
      {
        // We're not really interested in QueryInterface's HRESULT since it's
        // either S_OK or E_NOINTERFACE, hr will typically explain nothing special.
        // More important is whether we finally obtained the pointer or not
      }
    }
    

提交回复
热议问题