I know that modern Windows versions reclaim memory that was previously acquired with malloc
, new
and the like, after program termination, but what about COM objects? Should I call obj->Release()
on them on program's exit, or will the system do this for me?
My guess it: it depends. For out of process COM, I should probably always call Release()
, but for in-process COM, I think it really doesn't matter, because the COM objects die after program termination anyway.
If you're in the process itself then yes you should as you might not know where the server is and the server could be out of proc. If you're in a DLL it becomes more complicated.
In a DLL you should UNLESS you receive a
DLL_PROCESS_DETACH
notification, in which case you should do absolutely nothing and just let the application close. This is because this notification is called during process teardown. As such it is too late to clean up at that point. The kernel may have already reclaimed the blocks you callrelease
on.Remember as a DLL writer there is nothing you can do if the process exits ungracefully, you can only do what you can within reason to clean up after yourself in a graceful exit.
One easy solution is to use smart COM Pointers everywhere, the ATL and WRL have implementations that work nicely and make it so you don't have to worry about it for the most part. Even if these are stored statically their destructors will be called before process teardown or DLL unload, thus releasing safely at a time when it is safe to do so.
So the short answer is If you can e.g. you should always call
release
if it is safe to do so. However there are times when it is not and you should most definitely NOT do anything.