new(std::nothrow) 而不是 new 和错误处理
new(std::nothrow) instead of new and error handling
我正在学习 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;
我该如何处理这两种情况下的错误?
阅读 nothrow 的标准,它声称:
std::nothrow is a constant of type std::nothrow_t used to disambiguate the overloads of throwing and non-throwing allocation functions.
所以是的,本质上,这是一个 标志,让编译器知道要调用哪个分配函数,那是唯一的标准化函数。
关键字new将分配space,创建对象和return指向已分配 space.
中的新对象的指针
没有 nothrow
的 T *p = new T;
最好与 exceptions 一起用于错误报告,因为如果 new
fails 它在分配内存失败时抛出 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
选项,它将 return 一个空指针,然后我们可以像这样测试空指针:
T *p = new(std::nothrow) T;
if (p == nullptr) {
std::cout << "new T failed\n";
return 1;
}
我正在学习 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;
我该如何处理这两种情况下的错误?
阅读 nothrow 的标准,它声称:
std::nothrow is a constant of type std::nothrow_t used to disambiguate the overloads of throwing and non-throwing allocation functions.
所以是的,本质上,这是一个 标志,让编译器知道要调用哪个分配函数,那是唯一的标准化函数。
关键字new将分配space,创建对象和return指向已分配 space.
中的新对象的指针 没有nothrow
的 T *p = new T;
最好与 exceptions 一起用于错误报告,因为如果 new
fails 它在分配内存失败时抛出 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
选项,它将 return 一个空指针,然后我们可以像这样测试空指针:
T *p = new(std::nothrow) T;
if (p == nullptr) {
std::cout << "new T failed\n";
return 1;
}