Releasing a collection of COM interfaces by calling IUnknown::Release()

391 views Asked by At

In my application I need to defer releasing of COM interfaces until a later point. Therefor, I'm storing the interface pointers in std::vector<IUnknown*> COMInterfaces and later I loop through all the pointers and call Release() like so:

for(IUnknown* item : COMInterfaces) item->Release();

In the following link, in section 4.1.3, however, I read:

In COM, only interfaces are reference counted, not the objects themselves. After a client has obtained a reference to a particular interface, it must call the release method on exactly that interface, and not a different interface referring to the same object.

So, now I'm a bit confused whether it's ok to release interfaces polymorphically or not. I can't find any documentation that clearly states if this is ok or not.

Edit: Comments below confirm that this works and I'm going to use it like this. However, any pointers to an official documentation would be welcome as well as any explanation on why sometimes I see the following code (this is also how SafeRelease() is defined by Microsoft)

template<class T>
void Release(T*& comInterface) {
    if(comInterface) {
      comInterface->Release();
      comInterface = nullptr;
    }
}

instead of

void Release(IUnknown*& comInterface) {
    if(comInterface) {
      comInterface->Release();
      comInterface = nullptr;
    }
}
0

There are 0 answers