We have some legacy software code, which uses COM. I've noticed that at one place, we perform a queryInterface on an IInspectable pointer, but dont bother calling release.
For ex:
void foo(IInspectable* myInterface) { ComPtr<OBJTYPE> pObj; auto hr = myInterface->QueryInterface(__uuidof(SomeType),&pObj); if (hr != S_OK) { return hr; } //some code that uses pObj } I added Release to the above code like below :
auto hr = myInterface->QueryInterface(__uuidof(SomeType),&pObj); if (hr != S_OK) { return hr; } myInterface->Release(); //<-- Is this the correct way to release ? //some code that uses pObj; But I see that the above code crashes at times in the above function during release. Is there something wrong in the way I'm releasing the interface ? I can confirm that myInterface is not being used anywhere else in the function after the Release statement.
Apologies for not being able to copy/paste the actual code, but the above code summarizes pretty much the suspect code that I'm debugging. Basically what I want to know is, in the above scenario, do I need to call Release() ? And is this is the right place/way to call Release() ? Do I need to add any other safety checks in place ?
ComPtrdestructor will callReleasefor you. Explicitly calling it will cause a double-delete bug. Since you are passingmyInterfaceas a plain pointer, it means that no ownership on the interface is transferred; this is a non-owning pointer. You are only responsible for theOBJTYPEinterface, andComPtrdoes that for you.Microsoft::WRL::ComPtris a COM smart-pointer very similar to ATL'sCComPtr. You don't need to callReleaseexplicitly because the smart-pointer does that for you. See ComPtr. C++/WinRT has a similarwinrt::com_ptryou can use instead of WRL.