名稱空間
變體
操作

std::nothrow

來自 cppreference.com
< cpp‎ | 記憶體‎ | 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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2510 C++11 預設建構函式不是 explicit 的,可能導致歧義 改為 explicit

[編輯] 參見

分配函式
(函式) [編輯]