CoCreateInstance Return Value Processing

Here is a sample code that creates a COM object:

CComPtr<IBaseFilter> pFilter; auto hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<void**>(&pFilter)); 

I saw somewhere that checking that CoCreateInstance() succeeded should look like this:

 if (SUCCEEDED(hr) && pFilter != nullptr) { // code goes here } 

What if I would check only hr ? Wouldn't it be enough? Should I also check that filter != nullptr ?

 //would this be enough? if (SUCCEEDED(hr)) { // code goes here } 

This question also applies to other COM methods, such as QueryInterface() .

+4
source share
2 answers

Having an 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 detect problems in a timely manner, you can use ATLASSERT to compare with NULL . This does not generate code in release builds, but generates an early warning when debugging if something goes wrong (for example, you edit or copy the paste code later and change the logic for getting the pointer.

 CComPtr<IBaseFilter> pFilter; HRESULT hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<VOID**>(&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<IDMOWrapperFilter> pDmoWrapperFilter = pFilter; if(pDmoWrapperFilter) { // We're not really interested in QueryInterface 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 } } 
+6
source

I think it is redundant and not needed to test both.

If this is not the case, the return value will tell you what error occurred. That is why there are two ways to determine if this function was successful or not.

0
source