Namespaces
Variants

std::nothrow

来自 zh.cppreference.net
 
 
 
内存管理库
分配器
内存资源
未初始化存储 (直到 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 默认构造函数为非显式,可能导致歧义 改为显式

另请参阅

分配函数
(函数)