c++createinstance

Does CreateInstance objects need to be expicitly destroyed in the destructor?


This is my constructor:

CMSATools::CMSATools()
{
    m_pInterface = NULL;

    HRESULT hr;
    hr = m_pInterface.CreateInstance(__uuidof(MSAToolsLibrary::MSAToolsLibraryClass));
    if (FAILED(hr))
    {
        // TODO     }
}

m_pInterface is defined:

MSAToolsLibrary::IMSAToolsLibraryInterfacePtr m_pInterface;

Solution

  • If m_pInterface is a smart COM object pointer, like CComPtr, you do not need to explicitly destroy it. When the smart pointer goes out of scope, like when the ~CMSATools destructor is called, or when the smart pointer is assigned a new value, it decrements the reference count of the COM object that it is currently holding a pointer to. When the COM object's reference count falls to 0, it destroys itself.