名稱空間
變體
操作

std::bad_array_new_length

來自 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>
class bad_array_new_length;
(C++11 起)

std::bad_array_new_length 是由 new 表示式 丟擲的異常型別,用於報告以下情況的無效陣列長度:

  1. 陣列長度為負數,
  2. 新陣列的總大小將超過實現定義的預設最大值,
  3. 初始化子句的數量超過要初始化的元素數量。

只有第一個陣列維度可能產生此異常;除了第一個維度之外的維度是常量表達式,並在編譯時進行檢查。

cpp/error/exceptioncpp/memory/new/bad allocstd-bad array new length-inheritance.svg

繼承圖

目錄

[編輯] 成員函式

(建構函式)
構造一個新的 bad_array_new_length 物件
(公開成員函式)
operator=
替換 bad_array_new_length 物件
(公開成員函式)
what
返回解釋字串
(公開成員函式)

std::bad_array_new_length::bad_array_new_length

bad_array_new_length() noexcept;
(1) (C++11 起)
bad_array_new_length( const bad_array_new_length& other ) noexcept;
(2) (C++11 起)

構造一個新的 bad_array_new_length 物件,其包含一個實現定義的以 null 結尾的位元組字串,該字串可透過 what() 訪問。

1) 預設建構函式。
2) 複製建構函式。如果 *thisother 都具有動態型別 std::bad_array_new_length,則 std::strcmp(what(), other.what()) == 0

引數

其他 - 要複製的另一個異常物件

std::bad_array_new_length::operator=

bad_array_new_length& operator=( const bad_array_new_length& other ) noexcept;
(C++11 起)

other 的內容替換當前物件的內容。如果 *thisother 都具有動態型別 std::bad_array_new_length,則賦值後 std::strcmp(what(), other.what()) == 0

引數

其他 - 用於賦值的另一個異常物件

返回值

*this

std::bad_array_new_length::what

virtual const char* what() const noexcept;
(C++11 起)
(C++26 起為 constexpr)

返回解釋字串。

返回值

指向一個實現定義的、以 null 結尾的字串的指標,其中包含解釋性資訊。該字串適合轉換為 std::wstring 並顯示。該指標保證在從其獲取的異常物件被銷燬之前,或在該異常物件上呼叫非 const 成員函式(例如複製賦值運算子)之前,始終有效。

在常量求值期間,返回的字串使用普通字面量編碼進行編碼。

(C++26 起)

注意

允許但不要求實現重寫 what()

繼承自 std::bad_alloc

繼承自 std::exception

成員函式

銷燬異常物件
(std::exception 的虛公共成員函式) [編輯]
[virtual]
返回解釋字串
(std::exception 的虛公共成員函式) [編輯]

[編輯] 注意

特性測試 標準 特性
__cpp_lib_constexpr_exceptions 202411L (C++26) 異常型別的 constexpr

[編輯] 示例

應該丟擲 std::bad_array_new_length 的三種情況

#include <climits>
#include <iostream>
#include <new>
 
int main()
{
    try
    {
        int negative = -1;
        new int[negative];
    }
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "1) " << e.what() << ": negative size\n";
    }
 
    try
    {
        int small = 1;
        new int[small]{1,2,3};
    }
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "2) " << e.what() << ": too many initializers\n";
    }
 
    try
    {
        long large = LONG_MAX;
        new int[large][1000];
    } 
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "3) " << e.what() << ": too large\n";
    }
 
    std::cout << "End\n";
}

可能的輸出

1) std::bad_array_new_length: negative size
2) std::bad_array_new_length: too many initializers
3) std::bad_array_new_length: too large
End

[編輯] 參閱

分配函式
(函式) [編輯]
記憶體分配失敗時丟擲的異常
(類) [編輯]