std::nothrow
来自 cppreference.cn
定义于头文件 <new> |
||
(1) | ||
struct nothrow_t {}; |
(C++11 前) | |
struct nothrow_t { explicit nothrow_t() = default; }; |
(C++11 起) | |
extern const std::nothrow_t nothrow; |
(2) | |
std::nothrow_t
是一个空的类类型,用于区分抛出异常和不抛出异常的分配函数的重载。std::nothrow
是它的一个常量。
[编辑] 示例
运行此代码
#include <iostream> #include <new> int main() { try { while (true) { new int[100000000ul]; // throwing overload } } catch (const std::bad_alloc& e) { std::cout << e.what() << '\n'; } while (true) { int* p = new(std::nothrow) int[100000000ul]; // non-throwing overload if (p == nullptr) { std::cout << "Allocation returned nullptr\n"; break; } } }
输出
std::bad_alloc Allocation returned nullptr
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 2510 | C++11 | 默认构造函数不是 explicit 的,可能导致歧义 | 改为 explicit |
[编辑] 参见
分配函数 (函数) |