命名空间
变体
操作

std::nothrow

来自 cppreference.cn
< cpp‎ | memory‎ | new
 
 
 
内存管理库
(仅为演示目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
定义于头文件 <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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2510 C++11 默认构造函数是非显式的,这可能导致歧义 设为显式

[编辑] 参见

分配函数
(函数) [编辑]