全局关闭C++新运算符异常

Turn off C++ new operator exceptions globally

本文关键字:运算符 异常 C++ 全局      更新时间:2023-10-16

是否有任何方法可以全局关闭new运算符的异常?如果不止一个,哪一个最好?

我试过这个,但我真的不确定:

#include <new>
using std::nothrow;

我试着在谷歌上搜索"使用std::nothrow;",但没有结果。

我正在使用MSVC 2010。

我当然知道new (std::nothrow) myClass();

否。这会破坏很多代码,例如标准标头中的代码,而标准标头确实依赖于new抛出。

C++委员会意识到在一个名称下标准化几十种几乎兼容的语言所带来的危险,如果只有5种这样的选项,你就已经有32种不兼容的语言了。

#define NEW1(type, ...) new (std::nothrow) type(__VA_ARGS__)
#define NEW(type, size, ...) new (std::nothrow) type[size](__VA_ARGS__)

//用法:

int *a=NEW1(int),     //single non-initialized int
    *b=NEW1(int, 42), //single int with value 42
    *c=NEW(int, 42);  //array of ints made of 42 elements
delete a;
delete b;
delete[] c;