检查失败的新
为什么此 ATL/COM 代码检查分配是否成功?我希望通过 CoGetALloc 或某些此类 api 可以看到自定义分配。符合标准的 C++ 运行时应该抛出 std::bad_alloc,但话又说回来,分配器可能确实已被换成了不抛出的 impl。
DDClientData* pNewData = new DDClientData();
if (pNewData==NULL)
return E_OUTOFMEMORY;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
COM 方法不允许释放异常 - 实现可以引发异常,但必须在异常转义方法并转换为适当的 HRESULT 之前对其进行处理。
上面的代码不会达到预期的效果 - 一旦
new
失败,std::bad_alloc
就会被抛出,并且不会执行对空指针的检查。该实现必须将new
调用包装到try
-catch
中,或者将整个方法实现包装到try
-抓住
。 ATL 通常在新
调用。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
failsstd::bad_alloc
is thrown and the check for a null pointer is not executed. The implementation has to either wrap thenew
call intotry
-catch
or wrap the whole method implementation intotry
-catch
. ATL usually uses _ATLTRY-like macros around thenew
call.COM 不使用异常:任何 COM 对象都应该在失败时返回有效的
HRESULT
。另外,还有关于在退出时设置返回值的保证,任何符合标准的 COM 对象都必须遵守。由于这些原因,异常在 COM/ATL 中表现不佳,并且在 Microsoft[1] 内部根本不使用,甚至不用于分配。上面显示的代码示例只是反映了该约定。[1] Sez me,一名 MS FTE。 MS 的 COM 组件是在禁用 C++ 异常的情况下编译的。
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.