问题描述
我知道根据 C++ 标准,如果 new 无法分配内存,它应该抛出 std::bad_alloc 异常.但我听说有些编译器如 VC6(或 CRT 实现?)不遵守它.这是真的 ?我问这个是因为在每个新语句之后检查 NULL 会使代码看起来非常难看.
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 在这方面默认是不合规的.VC6的new
返回0
(或NULL
).
VC6 was non-compliant by default in this regard. VC6's new
returned 0
(or NULL
).
这是微软关于这个问题的知识库文章以及他们建议的使用自定义 new
处理程序的解决方法:
Here's Microsoft's KB Article on this issue along with their suggested workaround using a custom new
handler:
- 在 Visual C++ 中,Operator new 不会在失败时引发 bad_alloc 异常
如果您有为 VC6 行为编写的旧代码,您可以通过链接名为 nothrownew.obj
的对象文件,使用较新的 MSVC 编译器(例如 7.0 及更高版本)获得相同的行为.实际上有一个相当复杂的一组规则7.0 和 7.1 编译器(VS2002 和 VS2003)来确定它们是默认不抛出还是抛出 new
.
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
.
似乎 MS 在 8.0 (VS2005) 中对此进行了清理—现在它总是默认为抛出新的,除非你特别链接到 nothrownew.obj
.
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
.
请注意,您可以指定您希望 new
返回 0
而不是使用 std 抛出
参数:std::bad_alloc
::nothrow
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;
这似乎在 VC6 中有效,因此它可能是一种或多或少机械地修复代码的方法,以便在所有编译器中都能正常工作,这样您就不必重新处理现有的错误处理.
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.
这篇关于在任何情况下 new 都会返回 NULL 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!