Why is a QueryInterface()
call always followed by a Release()
call? For example, I have seen a sample code from MSDN as below:
HRESULT hr = S_OK;
CDecoder *pObj = new CDecoder(&hr);
if (SUCCEEDED(hr))
{
*ppv = NULL;
hr = pObj->QueryInterface(riid, ppv);
}
pObj->Release();
return hr;
can someone explain the intent behind Release()
call here?
Because
QueryInterface
will callAddRef
which increases the reference count to the pointer. When there are 0 references to a pointer it is freed for you.Note: There is some confusion in this question's answers about what
QueryInterface
actually does. It simply retrieves pointers to the supported interfaces on an object and increments the reference count on that object. It doesn't create a new object for each interface that it implements.For example if you have an object which implements 2 interfaces, then the call would simply cast that object as each of the interface and increment a variable which is used as the reference count.
Note: The reference counting can be implemented in different ways, but the above explains the usual scenario. In particular @Ben describes a tear off interface below which stresses the importance of calling Release on the interface pointer that was returned to you.