c++memory-leakscomvisual-c++-6delete-operator

Memory leak - release and delete


IFSUPCUTILSize* size = NULL;
CoCreateInstance(CLSID_UTILSize, NULL, CLSCTX_INPROC_SERVER, IID_IFSUPCUTILSize,    reinterpret_cast<void**>(&size));
            
if (size != NULL){
size->Release();
size = NULL;
}
delete size;

Do I need "delete size" in the code above? If I include "delete size", will I have a memory leak because I did not use New? Or is there a New inside the call to CoCreateInstance. I built this with VC++ 6.


Solution

  • COM interfaces are reference counted. CoCreateInstance() returns an interface pointer to a COM object whose reference count has already been incremented. Calling Release() decrements the reference count. When the reference count falls to zero, the COM object frees itself automatically. DO NOT call delete on a COM interface pointer! Always use Release() only.