我知道根据C ++标准,如果新的失败分配内存,它应该抛出std :: bad_alloc异常。但我听说有些编译器如VC6(或CRT实现?)不坚持它。这是真的 ?我问这是因为检查NULL后,每一个新的语句使代码看起来很丑陋。
解决方案VC6在这方面默认不合规。 VC6的 new 返回 0 (或 NULL )。 p>
这是Microsoft的知识库文章以及他们建议的解决方法,使用自定义新处理程序:
- 新操作员不会在失败时抛出bad_alloc异常在Visual C ++
如果你有为VC6行为编写的旧代码,你可以得到更新的通过在名为 nothrownew.obj 的对象文件中链接MSVC编译器(类似于7.0及更高版本)。实际上在7.0和7.1编译器中有一个一组相当复杂的规则 VS2002和VS2003),以确定他们是否默认为非抛出或抛出 new 。
href =msdn.microsoft/en-us/library/kftdy56f.aspx> MS清理这一点在8.0(VS2005)现在,它总是默认为一个新的除非你具体链接到 nothrownew.obj 。
请注意,您可以指定要 / code>使用来返回 0 ,而不是抛出 std :: bad_alloc std :: nothrow 参数:
SomeType * p = new(std :: nothrow)SomeType;这似乎在VC6中工作,因此它可能是一种或多或少机械修复代码的方式与所有编译器一样工作,因此您不必重新处理现有的错误处理。
I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement makes code look very ugly.
解决方案VC6 was non-compliant by default in this regard. VC6's new returned 0 (or NULL).
Here's Microsoft's KB Article on this issue along with their suggested workaround using a custom new handler:
- Operator new does not throw a bad_alloc exception on failure in Visual C++
If you have old code that was written for VC6 behavior, you can get that same behavior with newer MSVC compilers (something like 7.0 and later) by linking in a object file named nothrownew.obj. There's actually a fairly complicated set of rules in the 7.0 and 7.1 compilers (VS2002 and VS2003) to determine whether they defaulted to non-throwing or throwing new.
It seems that MS cleaned this up in 8.0 (VS2005)—now it always defaults to a throwing new unless you specifically link to nothrownew.obj.
Note that you can specify that you want new to return 0 instead of throwing std::bad_alloc using the std::nothrow parameter:
SomeType *p = new(std::nothrow) SomeType;This appears to work in VC6, so it could be a way to more or less mechanically fix the code to work the same with all compilers so you don't have to rework existing error handling.
更多推荐
在任何情况下,新的返回NULL?
发布评论