When working in the unmanaged world, we have to make sure that we clean up after ourselves if we have allocated memory on the heap (e.g. by using the new
keyword in C++); we also have to make sure that we AddRef
COM components that are created using CreateInstance
and to Release
it later; perhaps something like:
SomeNameSapce::IObjPtr obj;
HRESULT hr = obj.CreateInstance(L"SomeObject");
if (hr == S_OK)
{
obj->AddRef();
m_anotherObj= obj->GetObj();
obj->Release();
}
Obviously we could use smart pointers and other such things (in C++) but that's besides the point...
Do we also have to AddRef/Release
for objects that are grabbed from COM components (like m_anotherObj in the example above)?
To make things more confusing, what happens if this particular component that is actually a .NET component which is being exposed to unmanaged code via a COM interface? Does the garbage collector know to clear stuff up or does it all have to be done manually in the unmanaged world?