Namespaces
Variants

std:: nothrow

From cppreference.net
< cpp ‎ | memory ‎ | new
Utilities library
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
定义于头文件 <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];   // 抛出异常的重载
        }
    }
    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 默认构造函数为非显式,可能导致歧义 改为显式

另请参阅

分配函数
(函数)