名稱空間
變體
操作

std::out_of_range

來自 cppreference.com
< cpp‎ | 錯誤
定義於標頭檔案 <stdexcept>
class out_of_range;

定義一種作為異常丟擲的物件型別。它報告由於嘗試訪問超出定義範圍的元素而導致的錯誤。

它可能由 std::bitsetstd::basic_string 的成員函式、std::stoistd::stod 函式族,以及邊界檢查成員訪問函式(例如 std::vector::atstd::map::at)丟擲。

cpp/error/exceptioncpp/error/logic errorstd-out of range-inheritance.svg

繼承圖

目錄

[編輯] 成員函式

(建構函式)
構造一個帶給定訊息的新 out_of_range 物件
(公開成員函式)
operator=
替換 out_of_range 物件
(公開成員函式)

std::out_of_range::out_of_range

out_of_range( const std::string& what_arg );
(1)
out_of_range( const char* what_arg );
(2)
out_of_range( const out_of_range& other );
(3) (C++11 起無異常丟擲)
1) 使用 what_arg 作為解釋字串構造異常物件。構造後,std::strcmp(what(), what_arg.c_str()) == 0
2) 使用 what_arg 作為解釋字串構造異常物件。構造後,std::strcmp(what(), what_arg) == 0
3) 複製建構函式。如果 *thisother 都具有動態型別 std::out_of_range,則 std::strcmp(what(), other.what()) == 0。複製建構函式不能丟擲異常。

引數

what_arg - 解釋性字串
其他 - 要複製的另一個異常物件

異常

1,2) 可能丟擲 std::bad_alloc

注意

因為複製 std::out_of_range 不允許丟擲異常,所以此訊息通常在內部儲存為單獨分配的引用計數字符串。這也是為什麼沒有接受 std::string&& 的建構函式:它仍然必須複製內容。

LWG issue 254 解決之前,非複製建構函式只能接受 std::string。為了構造一個 std::string 物件,這使得動態分配成為強制性的。

LWG issue 471 解決之後,派生的標準異常類必須有一個可公開訪問的複製建構函式。只要透過 what() 獲取的解釋字串對於原始物件和複製物件是相同的,就可以隱式定義它。

std::out_of_range::operator=

out_of_range& operator=( const out_of_range& other );
(C++11 起無異常丟擲)

將內容賦值為 other 的內容。如果 *thisother 都具有動態型別 std::out_of_range,則賦值後 std::strcmp(what(), other.what()) == 0。複製賦值運算子不能丟擲異常。

引數

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

返回值

*this

注意

LWG issue 471 解決之後,派生的標準異常類必須有一個可公開訪問的複製賦值運算子。只要透過 what() 獲取的解釋字串對於原始物件和複製物件是相同的,就可以隱式定義它。

繼承自 std::logic_error

繼承自 std::exception

成員函式

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

[編輯] 註釋

標準錯誤條件 std::errc::result_out_of_range 通常表示結果(而不是輸入)超出範圍的情況,它與 std::range_errorERANGE 更密切相關。

[編輯] 缺陷報告

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

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 254 C++98 缺少接受 const char* 的建構函式 已新增
LWG 471 C++98 std::out_of_range 的解釋字串
解釋性字串是實現定義的
它們與原始 std::runtime_error 物件的
原始 std::out_of_range 物件

[編輯] 另見

帶邊界檢查訪問指定字元
(std::basic_string<CharT,Traits,Allocator> 的公共成員函式) [編輯]
帶邊界檢查訪問指定字元
(std::basic_string_view<CharT,Traits> 的公共成員函式) [編輯]
訪問指定的元素,帶邊界檢查
(std::deque<T,Allocator> 的公共成員函式) [編輯]
訪問指定的元素,帶邊界檢查
(std::map<Key,T,Compare,Allocator> 的公共成員函式) [編輯]
訪問指定的元素,帶邊界檢查
(std::unordered_map<Key,T,Hash,KeyEqual,Allocator> 的公共成員函式) [編輯]
訪問指定的元素,帶邊界檢查
(std::vector<T,Allocator> 的公共成員函式) [編輯]
訪問指定的元素,帶邊界檢查
(std::array<T,N> 的公共成員函式) [編輯]
(C++26)
訪問指定的元素,帶邊界檢查
(std::span<T,Extent> 的公共成員函式) [編輯]