Namespaces
Variants

std::nothrow

来自 zh.cppreference.net
< cpp | memory | new
 
 
 
内存管理库
分配器
内存资源
未初始化存储 (至C++20*)
垃圾收集支持 (至C++23)
 
 
定义于头文件 <new>
struct nothrow_t {};
(1) (至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];   // 抛出异常的重载
        }
    }
    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 << "Allocation returned nullptr\n";
            break;
        }
    }
}

输出:

std::bad_alloc
Allocation returned nullptr

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2510 C++11 默认构造函数为非显式,可能导致歧义 改为显式

另请参阅

分配函数
(函数)