Why was my COM factory never released during the program life cycle?

I have my own C ++ ATL in-proc COM server. Separate test program

  • calls CoInitialize() ,
  • calls CoCreateInstance() , then
  • calls the pointer Release() on the pointer,
  • then calls CoUnitialize() and exits.

If I run the test program in the Visual C ++ debugger, the debug CRT reports one memory leak and every time the distribution number matches.

I used selection binding and found that an object not returned to the heap is an object of class factory.

So basically the following happens:

  • program calls CoCreateInstance()
  • COM internal call DllGetClassObject()
  • ATL creates a factory instance and transfers ownership to the caller (inside COM)

and then factory is never released - I don't see enough calls to Release() of the factory class.

What's happening? Is this a runtime COM defect?

+3
source share
1 answer

It turns out that this is an ATL implementation issue.

The server uses a global instance of the CComModule class. When CComModule::DllClassObject() is called, it creates an instance of the factory class and caches it in the map referenced by the CComModule object. So in fact, the CComModule object belongs to the factory class. When the CComModule runs the destructor, it does not release cached class factories.

To free all cached class factories of CComModule::Term() , the method must be called before the server is unloaded. IMO the purest way to achieve this is to output from CComModule and call CComModule::Term() in the destructor of the derived class.

+2
source

All Articles