我正在学习 new 和 delete,但我不太理解下面代码中的 nothrow
部分。
我知道 std::nothrow
是为了通知编译器不要抛出异常,但是还有其他原因要写 std::nothrow
吗?
我不完全理解的代码是:
// Is there another reason to write:
T *p = new(nothrow) T;
// instead of this:
T *p = new T;
我该如何处理这两种情况下的错误?
最佳答案
关键词new将分配空间,创建对象并返回指向分配空间中的新对象的指针。
没有nothrow
的 T *p = new T;
最好与 exceptions 一起用于错误报告,因为如果 new
失败 它抛出 std::bad_alloc
或派生自 std::bad_alloc
的另一个异常(C++11 起) 分配内存失败。
例子:
T *p;
try {
p = new T;
}
catch(const std::bad_alloc &e) {
std::cout << "Error: " << e.what() << '\n';
}
如果您不使用异常来报告错误,那么您应该使用 nothrow
选项。
否则,当或如果 new 失败时,它将抛出一个异常。使用 nothrow
选项,它将返回一个空指针,然后我们可以像这样测试空指针:
T *p = new(std::nothrow) T;
if (p == nullptr) {
std::cout << "new T failed\n";
return 1;
}
关于c++ - new(std::nothrow) 而不是 new 和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664131/