Tutorial :checking for failed new



Question:

why does this ATL/COM code check for successful alloc? I would have expected a custom allocation to be visible through CoGetALloc or some such api. A standards-conforming C++ runtime should be throwing std::bad_alloc, but then again maybe the allocator has indeed been traded out for a non-throwing impl.

DDClientData* pNewData = new DDClientData();  if (pNewData==NULL)      return E_OUTOFMEMORY;  


Solution:1

COM methods are not allowed to let exceptions out - the implementation can throw exceptions, but it must handle them before they escape the method and translate to an appropriate HRESULT.

The code above will not have desired effect - once new fails std::bad_alloc is thrown and the check for a null pointer is not executed. The implementation has to either wrap the new call into try-catch or wrap the whole method implementation into try-catch. ATL usually uses _ATLTRY-like macros around the new call.


Solution:2

COM doesn't use exceptions: any COM object is supposed to return a valid HRESULT on failure. Plus there are guarantees about setting return values on exit, which any conforming COM object has to comply with. For these reasons, exceptions play badly with COM/ATL, and aren't used at all internally at Microsoft[1], not even for allocations. The code sample shown above simply reflects that convention.

[1] Sez me, an MS FTE. COM components at MS are compiled with C++ exceptions disabled.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »