std::nothrow

出自cppreference.com
< cpp | memory | new
(重新導向自cpp/memory/new/nothrow t
 
 
 
內存管理庫
(僅用於闡述*)
分配器
未初始化內存算法
受約束的未初始化內存算法
內存資源
未初始化存儲 (C++20 前)
(C++17 棄用)
(C++17 棄用)

垃圾收集器支持 (C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(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 << "分配返回了 nullptr\n";
            break;
        }
    }
}

輸出:

std::bad_alloc
分配返回了 nullptr

缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 出版時的行為 正確行為
LWG 2510 C++11 默認構造函數非顯式,可能導致歧義 讓它顯式

參閱

分配函數
(函數)