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